ctb_formats_time/
time.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Time parsing, formatting, and conversion functions.
21//!
22//! Note: Calculations and conversions may not be quite correct as it seems
23//! there is currently no Rust library that fully implements leap seconds.
24
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace crate prelude"
29)]
30pub(crate) use ctb_utilities::*;
31
32use jiff::civil::{Date, DateTime, Time};
33use jiff::tz::TimeZone;
34use jiff::{Span, Timestamp, Zoned};
35use std::str::FromStr;
36
37/// Parses an absolute epoch timestamp or relative duration like "7d", "24h", "60m".
38///
39/// Supports:
40/// - Raw epoch seconds (e.g. "1725846721")
41/// - RFC 3339 / ISO 8601 date and time strings (e.g. "2026-09-09T01:52:01Z", "2026-09-09")
42/// - Relative duration strings (e.g. "7d", "24h", "60m", "30s", "1 week")
43///   which are interpreted as being relative to current time (`now - duration`).
44///
45/// Note: Results may not be quite correct as it seems there is currently no Rust
46/// library that fully implements leap seconds.
47pub fn parse_time_spec(s: &str) -> Result<i64> {
48    let s = s.trim();
49    if s.is_empty() {
50        bail!("Empty time specification");
51    }
52
53    // 1. Raw epoch seconds integer
54    if let Ok(raw_sec) = s.parse::<i64>() {
55        return Ok(raw_sec);
56    }
57
58    // 2. RFC 3339 / ISO 8601 timestamp with date and time
59    if let Ok(ts) = Timestamp::from_str(s) {
60        return Ok(ts.as_second());
61    }
62
63    // 3. RFC 3339 / ISO 8601 date without timezone/time (e.g. "2026-09-09")
64    if let Ok(date) = Date::from_str(s) {
65        let dt = date.to_datetime(Time::midnight());
66        let zoned = dt
67            .to_zoned(TimeZone::UTC)
68            .context("Failed to convert date to UTC zoned datetime")?;
69        return Ok(zoned.timestamp().as_second());
70    }
71
72    // 4. ISO 8601 datetime without timezone (e.g. "2026-09-09T12:00:00")
73    if let Ok(dt) = DateTime::from_str(s) {
74        let zoned = dt
75            .to_zoned(TimeZone::UTC)
76            .context("Failed to convert datetime to UTC zoned datetime")?;
77        return Ok(zoned.timestamp().as_second());
78    }
79
80    // 5. Relative duration via Jiff friendly or ISO duration syntax
81    let s_lower = s.to_ascii_lowercase();
82    if let Ok(span) = Span::from_str(&s_lower) {
83        let now = Zoned::now();
84        let target = if s.starts_with('+') {
85            now.checked_add(span)
86                .context("Time addition overflowed supported range")?
87        } else {
88            now.checked_sub(span.abs())
89                .context("Time subtraction underflowed supported range")?
90        };
91        return Ok(target.timestamp().as_second());
92    }
93
94    bail!(
95        "Unrecognized time format: '{s}'. Expected timestamp (e.g. 1700000000, 2026-01-01) or relative duration (e.g. '7d', '24h', '60m')"
96    );
97}
98
99/// Formats an epoch timestamp in seconds to "YYYY-MM-DD HH:MM" in UTC.
100///
101/// Note: Results may not be quite correct as it seems there is currently no Rust
102/// library that fully implements leap seconds.
103pub fn format_timestamp(sec: i64) -> String {
104    if let Ok(ts) = Timestamp::from_second(sec) {
105        ts.strftime("%Y-%m-%d %H:%M").to_string()
106    } else {
107        // Fallback for extreme timestamps outside supported range
108        format!("{sec}")
109    }
110}
111
112/// Determines if a given year is a leap year in the proleptic Gregorian calendar.
113#[expect(
114    clippy::expect_used,
115    reason = "Divisors 4, 100, and 400 are non-zero constants"
116)]
117pub fn is_leap_year(year: i64) -> bool {
118    if let Ok(y) = i16::try_from(year) {
119        if let Ok(d) = Date::new(y, 1, 1) {
120            return d.in_leap_year();
121        }
122    }
123    (year.checked_rem(4).expect("divisor 4 is non-zero") == 0
124        && year.checked_rem(100).expect("divisor 100 is non-zero") != 0)
125        || (year.checked_rem(400).expect("divisor 400 is non-zero") == 0)
126}
127
128#[cfg(test)]
129#[allow(
130    clippy::panic,
131    clippy::expect_used,
132    clippy::unwrap_used,
133    clippy::unwrap_in_result,
134    clippy::panic_in_result_fn,
135    clippy::indexing_slicing,
136    clippy::arithmetic_side_effects,
137    reason = "Standard repository test boilerplate"
138)]
139mod tests {
140    use super::*;
141
142    #[crate::ctb_test]
143    fn test_parse_time_spec_epoch_seconds() {
144        assert_eq!(parse_time_spec("0").unwrap(), 0);
145        assert_eq!(parse_time_spec("1700000000").unwrap(), 1_700_000_000);
146        assert_eq!(parse_time_spec("-1000").unwrap(), -1000);
147    }
148
149    #[crate::ctb_test]
150    fn test_parse_time_spec_iso_and_rfc3339() {
151        assert_eq!(parse_time_spec("1970-01-01T00:00:00Z").unwrap(), 0);
152        assert_eq!(parse_time_spec("1970-01-01").unwrap(), 0);
153        assert_eq!(parse_time_spec("1970-01-02T00:00:00Z").unwrap(), 86400);
154    }
155
156    #[crate::ctb_test]
157    fn test_parse_time_spec_relative_durations() {
158        let now = Zoned::now().timestamp().as_second();
159
160        // 60m should be approx now - 3600 seconds
161        let t_60m = parse_time_spec("60m").unwrap();
162        assert!((now - t_60m - 3600).abs() <= 5);
163
164        // 24h should be approx now - 86400 seconds
165        let t_24h = parse_time_spec("24h").unwrap();
166        assert!((now - t_24h - 86400).abs() <= 5);
167
168        // Case insensitivity: 24H
169        let t_24h_upper = parse_time_spec("24H").unwrap();
170        assert!((now - t_24h_upper - 86400).abs() <= 5);
171
172        // 7d should be approx now - 7*86400 seconds
173        let t_7d = parse_time_spec("7d").unwrap();
174        assert!((now - t_7d - 7 * 86400).abs() <= 5);
175
176        // Friendly phrases like "1 week" or "30s"
177        let t_30s = parse_time_spec("30s").unwrap();
178        assert!((now - t_30s - 30).abs() <= 5);
179
180        let t_1w = parse_time_spec("1 week").unwrap();
181        assert!((now - t_1w - 7 * 86400).abs() <= 5);
182    }
183
184    #[crate::ctb_test]
185    fn test_parse_time_spec_invalid() {
186        parse_time_spec("").unwrap_err();
187        parse_time_spec("   ").unwrap_err();
188        parse_time_spec("not_a_time").unwrap_err();
189        parse_time_spec("7xyz").unwrap_err();
190    }
191
192    #[crate::ctb_test]
193    fn test_format_timestamp() {
194        assert_eq!(format_timestamp(0), "1970-01-01 00:00");
195        assert_eq!(format_timestamp(86400), "1970-01-02 00:00");
196        assert_eq!(format_timestamp(1_700_000_000), "2023-11-14 22:13");
197    }
198
199    #[crate::ctb_test]
200    fn test_is_leap_year() {
201        assert!(is_leap_year(2000));
202        assert!(is_leap_year(2024));
203        assert!(!is_leap_year(1900));
204        assert!(!is_leap_year(2023));
205        assert!(!is_leap_year(2025));
206    }
207}