Skip to main content

kanbrain_core/model/
time.rs

1//! Timestamps as stored in task files, and ages and durations as shown on screen.
2
3use chrono::{DateTime, Duration, Local, NaiveDateTime, TimeZone, Timelike};
4
5/// RFC 3339 with the local UTC offset, e.g. `2026-09-24T10:12:00+02:00`.
6const TIMESTAMP_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%:z";
7
8/// Local-time formats accepted when a timestamp is typed by hand.
9const 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
11/// Current local time truncated to whole seconds, so files round-trip exactly.
12pub fn now() -> DateTime<Local> {
13    let now = Local::now();
14    now.with_nanosecond(0).unwrap_or(now)
15}
16
17/// A timestamp in the stored format.
18pub fn fmt_ts(dt: DateTime<Local>) -> String {
19    dt.format(TIMESTAMP_FORMAT).to_string()
20}
21
22/// Accepts RFC 3339 plus the hand-typing friendly local formats above.
23pub 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
34/// How long ago, rounded down: `<1m`, `5m`, `3h`, `2d`, `6w`.
35pub fn fmt_age(d: Duration) -> String {
36    let minutes = d.num_minutes().max(0);
37    match minutes {
38        // An age is never none, though times are kept to the second and one read within it is exactly zero.
39        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
47/// `45m`, `1h 05m`; rounded down to whole minutes, but `<1m` for less than one: a report row or a total that took
48/// seconds isn't one that took none.
49pub 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
58/// `01:02:03` for a live clock.
59pub 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
64/// The time `spans` (start, end) cover, counting once what several cover at the same moment: two tasks
65/// worked on in parallel for an hour took an hour of the day, not two. Empty or reversed spans count nothing.
66pub 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;