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 ..60 => format!("{minutes}m"),
39 60..1440 => format!("{}h", minutes / 60),
40 1440..20160 => format!("{}d", minutes / 1440),
41 _ => format!("{}w", minutes / 10080),
42 }
43}
44
45pub fn fmt_dur(d: Duration) -> String {
47 let minutes = d.num_minutes().max(0);
48 if minutes >= 60 { format!("{}h {:02}m", minutes / 60, minutes % 60) } else { format!("{minutes}m") }
49}
50
51pub fn fmt_clock(d: Duration) -> String {
53 let s = d.num_seconds().max(0);
54 format!("{:02}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
55}
56
57pub fn covered(spans: impl IntoIterator<Item = (DateTime<Local>, DateTime<Local>)>) -> Duration {
60 let mut spans: Vec<_> = spans.into_iter().filter(|(start, end)| end > start).collect();
61 spans.sort_unstable();
62 let mut total = Duration::zero();
63 let mut open: Option<(DateTime<Local>, DateTime<Local>)> = None;
64 for (start, end) in spans {
65 match &mut open {
66 Some((_, until)) if start <= *until => *until = (*until).max(end),
67 _ => {
68 if let Some((from, until)) = open.replace((start, end)) {
69 total += until - from;
70 }
71 }
72 }
73 }
74 total + open.map_or_else(Duration::zero, |(from, until)| until - from)
75}
76
77#[cfg(test)]
78#[path = "../../tests/model/time.rs"]
79mod tests;