1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
use super::*;
use chrono::{offset::Utc, Local, NaiveDate};
// ----------------------------------------------------------------------------
#[derive(Debug, Clone)]
pub struct DateRange {
start: NaiveDate,
end: NaiveDate,
/// If user ever pressed button to set the end date, this is switched to `true`.
end_modified_by_user: bool,
#[allow(dead_code)]
/// Used to distinguish the `DatePickerButton`s from each other.
id_source: Option<String>,
}
impl DateRange {
pub fn new(start: &NaiveDate, end: &NaiveDate, id_source: Option<&str>) -> Self {
Self {
start: start.to_owned(),
end: end.to_owned(),
end_modified_by_user: false,
id_source: id_source.map(|id| id.to_owned()),
}
}
/// Sets range end to today (in `Utc`), and the range start to today (in `Utc`) minus offset.
pub fn today(start_day_offset: i64, id_source: Option<&str>) -> Self {
Self {
start: Utc::now().naive_utc().date() - Duration::days(start_day_offset),
end: Utc::now().naive_utc().date(),
end_modified_by_user: false,
id_source: id_source.map(|id| id.to_owned()),
}
}
/// Sets range end to today (in `Local`), and the range start to today (in `Local`) minus offset.
pub fn today_local(start_day_offset: i64, id_source: Option<&str>) -> Self {
let today = today_local();
Self {
start: today - Duration::days(start_day_offset),
end: today,
end_modified_by_user: false,
id_source: id_source.map(|id| id.to_owned()),
}
}
pub fn dates_between(&self) -> AnyResult<Vec<NaiveDate>> {
if self.start > self.end {
return Err(anyhow!(
"Invalid date range, start date must be prior to end date"
));
};
let mut dates = vec![];
let mut d = self.start.clone();
while d <= self.end {
dates.push(d);
d = d + Duration::days(1);
}
Ok(dates)
}
pub fn days_difference(&self) -> i64 {
(self.end - self.start).num_days()
}
/// Makes the dates between a range in `String`s.
pub fn dates_between_as_str(&self, fmt: &str) -> AnyResult<Vec<String>> {
Ok(self
.dates_between()?
.into_iter()
.map(|d| format!("{}", d.format(fmt)))
.collect())
}
/// Opinionatedlly sets range end to today. Used to avoid stale data, e.g. app set open for days.
/// However, to allow user to customize the end date, this only has effect
/// when user never clicked on the `Self::end_button`.
/// Using `Utc::today`.
pub fn end_today_mut_if_unmodified(&mut self) {
if !self.end_modified_by_user {
debug!("Updating date range end to today (UTC)");
self.end = Utc::now().naive_local().date();
}
}
pub fn end_today_local_mut_if_unmodified(&mut self) {
if !self.end_modified_by_user {
debug!("Updating date range end to today (Local)");
self.end = today_local();
}
}
pub fn start_datetime(&self) -> DateTime<Utc> {
naive_date_to_utc(&self.start, 0, 0, 0)
}
pub fn end_datetime(&self) -> DateTime<Utc> {
naive_date_to_utc(&self.end, 23, 59, 59)
}
}
#[cfg(feature = "gui")]
impl DateRange {
#[cfg(any(feature = "query_message", feature = "review_item"))]
/// [`DatePickerButton`] to choose the start of the date range.
/// NOTE: `Self::id_source` must be `is_some`.
fn start_button_unwrap(&mut self, ui: &mut egui::Ui) -> egui::Response {
ui.add(
DatePickerButton::new(&mut self.start)
.id_source(&format!("{}_start", self.id_source.as_ref().unwrap())),
)
}
#[cfg(any(feature = "query_message", feature = "review_item"))]
/// [`DatePickerButton`] to choose the end of the date range with detection for click.
/// NOTE: `Self::id_source` must be `is_some`.
fn end_button_unwrap(&mut self, ui: &mut egui::Ui) -> egui::Response {
let response = ui.add(
DatePickerButton::new(&mut self.end)
.id_source(&format!("{}_end", self.id_source.as_ref().unwrap())),
);
// since `egui::Response::changed` not working for `DatePickerButton`
if response.clicked() {
self.end_modified_by_user = true;
};
response
}
#[cfg(any(feature = "query_message", feature = "review_item"))]
/// Two [`DatePickerButton`] to modify the start and end of date range.
pub fn ui(&mut self, ui: &mut egui::Ui) {
self.start_button_unwrap(ui);
self.end_button_unwrap(ui);
}
#[cfg(any(feature = "query_message", feature = "review_item"))]
/// Two [`DatePickerButton`] to modify only the start of date range.
pub fn ui_end_range_disabled(&mut self, ui: &mut egui::Ui) {
self.start_button_unwrap(ui);
// ui.add_enabled(
// false,
// DatePickerButton::new(&mut self.end).id_source(&format!("{}_end", self.id_source)),
// );
}
}
impl fmt::Display for DateRange {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "From {} to {}", self.start, self.end)
}
}
/// Manually sets the year-month-day of `Local` to `Utc`.
fn today_local() -> NaiveDate {
Local::now().date_naive()
}
fn naive_date_to_utc(date: &NaiveDate, hour: u32, min: u32, sec: u32) -> DateTime<Utc> {
DateTime::<Utc>::from_local(date.and_hms_opt(hour, min, sec).unwrap(), Utc)
}
#[cfg(test)]
mod tests {
use super::*;
// #[test]
// fn dates_between() {
// // correct range
// let dates = DateRange::today(6).dates_between();
// eprintln!("Dates between: {:?}", dates);
// assert!(dates.is_ok());
// // wrong range
// let dates = DateRange::new(
// &NaiveDate::from_ymd(2021, 4, 1),
// &NaiveDate::from_ymd(2021, 3, 1),
// )
// .dates_between();
// assert!(dates.is_err());
// }
#[test]
fn local_today() {
use chrono::{Datelike, TimeZone};
// let local = Local::now().naive_local();
let local = Local::now();
eprintln!(
"LOCAL NAIVE TIME: {} - {} - {}",
local.year(),
local.month(),
local.day()
);
// let utc = Utc::now().naive_local();
// eprintln!("UTC NAIVE TIME: {}", utc);
// let utc = Utc.ymd(local.year(), local.month(), local.day());
let utc = Utc.with_ymd_and_hms(2023, 12, 2, 0, 0, 0).unwrap();
eprintln!("UTC DATE FROM LOCAL: {}", utc);
}
}