Files
nexus/crates/nexus-core/src/time.rs
2026-11-09 17:39:03 +01:00

62 lines
1.9 KiB
Rust

//! UTC-Zeitstempel im Format ISO 8601 ohne zusätzliche Abhängigkeit.
use std::time::{SystemTime, UNIX_EPOCH};
/// Sekunden seit 1970 als `2026-11-09T16:20:00Z`.
pub fn iso8601_from_unix(secs: u64) -> String {
let days = (secs / 86_400) as i64;
let rest = secs % 86_400;
let (year, month, day) = civil_from_days(days);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
rest / 3600,
rest % 3600 / 60,
rest % 60
)
}
/// Jetzt als `2026-11-09T16:20:00Z`.
pub fn now_iso8601() -> String {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
iso8601_from_unix(secs)
}
/// Tage seit 1970-01-01 in (Jahr, Monat, Tag), Algorithmus von Howard Hinnant.
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 doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
let year = yoe + era * 400 + i64::from(month <= 2);
(year, month, day)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bekannte_zeitpunkte() {
assert_eq!(iso8601_from_unix(0), "1970-01-01T00:00:00Z");
assert_eq!(iso8601_from_unix(1_700_000_000), "2023-11-14T22:13:20Z");
// Schalttag
assert_eq!(iso8601_from_unix(951_782_400), "2000-02-29T00:00:00Z");
assert_eq!(iso8601_from_unix(1_709_164_800), "2024-02-29T00:00:00Z");
assert_eq!(iso8601_from_unix(4_102_444_799), "2099-12-31T23:59:59Z");
}
#[test]
fn jetzt_hat_das_erwartete_format() {
let now = now_iso8601();
assert_eq!(now.len(), 20);
assert!(now.starts_with("20") && now.ends_with('Z'));
}
}