1.5 KiB · text History 263b40b
//! Timestamp formatting helpers.

use chrono::{DateTime, FixedOffset, Utc};

/// Absolute timestamp, e.g. `2026-06-30 19:27` (used for tooltips).
pub fn abs(ts: DateTime<FixedOffset>) -> String {
    ts.format("%Y-%m-%d %H:%M").to_string()
}

/// Compact relative age: `now`, `5m`, `22h`, `3d`, `7w`, `4mo`, `2y`.
///
/// Note: minutes are `m`, months are `mo` (to disambiguate the two).
pub fn rel(ts: DateTime<FixedOffset>) -> String {
    let secs = (Utc::now() - ts.with_timezone(&Utc)).num_seconds();
    if secs < 60 {
        return "now".to_string();
    }
    let (minutes, hours, days) = (secs / 60, secs / 3600, secs / 86400);
    if minutes < 60 {
        format!("{minutes}m")
    } else if hours < 24 {
        format!("{hours}h")
    } else if days < 7 {
        format!("{days}d")
    } else if days < 30 {
        format!("{}w", days / 7)
    } else if days < 365 {
        format!("{}mo", days / 30)
    } else {
        format!("{}y", days / 365)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration;

    fn ago(d: Duration) -> String {
        rel((Utc::now() - d).into())
    }

    #[test]
    fn relative_units() {
        assert_eq!(ago(Duration::seconds(10)), "now");
        assert_eq!(ago(Duration::minutes(5)), "5m");
        assert_eq!(ago(Duration::hours(22)), "22h");
        assert_eq!(ago(Duration::days(3)), "3d");
        assert_eq!(ago(Duration::days(21)), "3w");
        assert_eq!(ago(Duration::days(120)), "4mo");
        assert_eq!(ago(Duration::days(800)), "2y");
    }
}