74 lines
2.2 KiB
Rust
74 lines
2.2 KiB
Rust
// 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");
|
||
}
|
||
}
|