[core] Time: RFC 3339 and long dates from Unix seconds

This commit is contained in:
2026-11-07 17:47:42 +01:00
parent 94ba18d38b
commit 7c81945771
2 changed files with 74 additions and 0 deletions
+1
View File
@@ -14,6 +14,7 @@ mod error;
mod model;
pub mod routes;
pub mod share;
pub mod time;
mod validate;
pub use error::{ValidationError, ValidationErrors};
+73
View File
@@ -0,0 +1,73 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Unix seconds to calendar dates (UTC), for API timestamps and visitor pages. Pure: the
//! caller passes the time in.
/// Days since 1970-01-01 → (year, month 1–12, day 1–31). Howard Hinnant's `civil_from_days`.
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
/// `2026-11-14T14:20:00Z`.
pub fn rfc3339(unix: u64) -> String {
let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2);
let (y, m, d) = civil_from_days(secs.div_euclid(86_400));
let s = secs.rem_euclid(86_400);
format!(
"{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
s / 3600,
(s / 60) % 60,
s % 60
)
}
const MONTHS: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
/// `14 November 2026` (UTC).
pub fn long_date(unix: u64) -> String {
let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2);
let (y, m, d) = civil_from_days(secs.div_euclid(86_400));
let month = MONTHS
.get(m.saturating_sub(1) as usize)
.copied()
.unwrap_or("?");
format!("{d} {month} {y}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_dates() {
assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z");
assert_eq!(rfc3339(951_782_400), "2000-02-29T00:00:00Z");
assert_eq!(rfc3339(1_794_666_000), "2026-11-14T14:20:00Z");
assert_eq!(long_date(1_794_666_000), "14 November 2026");
assert_eq!(long_date(4_133_980_799), "31 December 2100");
}
}