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: `0m`, `5m`, `3h`, `2d`, `6w`.
35pub 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
45/// `45m`, `1h 05m`; rounded down to whole minutes.
46pub 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
51/// `01:02:03` for a live clock.
52pub 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
57/// The time `spans` (start, end) cover, counting once what several cover at the same moment: two tasks
58/// worked on in parallel for an hour took an hour of the day, not two. Empty or reversed spans count nothing.
59pub 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;