kanbrain_core/model/
time.rs1use chrono::{DateTime, Duration, Local, NaiveDateTime, TimeZone, Timelike};
4
5const TIMESTAMP_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%:z";
7
8const HAND_TYPED_FORMATS: [&str; 4] = ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M"];
10
11pub fn now() -> DateTime<Local> {
13 let now = Local::now();
14 now.with_nanosecond(0).unwrap_or(now)
15}
16
17pub fn fmt_ts(dt: DateTime<Local>) -> String {
19 dt.format(TIMESTAMP_FORMAT).to_string()
20}
21
22pub fn parse_ts(s: &str) -> Option<DateTime<Local>> {
24 let s = s.trim();
25 if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
26 return Some(dt.with_timezone(&Local));
27 }
28 HAND_TYPED_FORMATS
29 .iter()
30 .find_map(|format| NaiveDateTime::parse_from_str(s, format).ok())
31 .and_then(|naive| Local.from_local_datetime(&naive).earliest())
32}
33
34pub fn fmt_age(d: Duration) -> String {
36 let minutes = d.num_minutes().max(0);
37 match minutes {
38 0 => "<1m".to_string(),
40 ..60 => format!("{minutes}m"),
41 60..1440 => format!("{}h", minutes / 60),
42 1440..20160 => format!("{}d", minutes / 1440),
43 _ => format!("{}w", minutes / 10080),
44 }
45}
46
47pub fn fmt_dur(d: Duration) -> String {
50 let minutes = d.num_minutes().max(0);
51 match minutes {
52 0 if d > Duration::zero() => "<1m".to_string(),
53 60.. => format!("{}h {:02}m", minutes / 60, minutes % 60),
54 _ => format!("{minutes}m"),
55 }
56}
57
58pub fn fmt_clock(d: Duration) -> String {
60 let s = d.num_seconds().max(0);
61 format!("{:02}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
62}
63
64pub fn covered(spans: impl IntoIterator<Item = (DateTime<Local>, DateTime<Local>)>) -> Duration {
67 let mut spans: Vec<_> = spans.into_iter().filter(|(start, end)| end > start).collect();
68 spans.sort_unstable();
69 let mut total = Duration::zero();
70 let mut open: Option<(DateTime<Local>, DateTime<Local>)> = None;
71 for (start, end) in spans {
72 match &mut open {
73 Some((_, until)) if start <= *until => *until = (*until).max(end),
74 _ => {
75 if let Some((from, until)) = open.replace((start, end)) {
76 total += until - from;
77 }
78 }
79 }
80 }
81 total + open.map_or_else(Duration::zero, |(from, until)| until - from)
82}
83
84#[cfg(test)]
85#[path = "../../tests/model/time.rs"]
86mod tests;