pub fn now_rfc3339() -> std::string::String {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
format_rfc3339_utc(secs)
}
fn format_rfc3339_utc(secs: u64) -> std::string::String {
let days = (secs / 86_400) as i64;
let time_of_day = secs % 86_400;
let hour = time_of_day / 3_600;
let minute = (time_of_day % 3_600) / 60;
let second = time_of_day % 60;
let (year, month, day) = civil_from_days(days);
std::format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
}
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
let doe = (z - era * 146_097) as u64; let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; let year = yoe as i64 + era * 400;
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 = if month <= 2 { year + 1 } else { year };
(year, month, day)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_epoch_formats_canonically() {
std::assert_eq!(format_rfc3339_utc(0), "1970-01-01T00:00:00Z");
}
#[test]
fn test_known_timestamp_formats_correctly() {
std::assert_eq!(format_rfc3339_utc(1_700_000_000), "2023-11-14T22:13:20Z");
}
#[test]
fn test_leap_day_formats_correctly() {
std::assert_eq!(format_rfc3339_utc(1_582_934_400), "2020-02-29T00:00:00Z");
}
#[test]
fn test_now_is_well_formed() {
let ts = now_rfc3339();
std::assert!(ts.ends_with('Z'), "must be UTC (Z): {ts}");
std::assert!(ts.starts_with("20"), "expected a 21st-century year: {ts}");
std::assert_eq!(ts.len(), 20, "YYYY-MM-DDTHH:MM:SSZ is 20 chars: {ts}");
std::assert_eq!(&ts[4..5], "-");
std::assert_eq!(&ts[10..11], "T");
std::assert_eq!(&ts[19..20], "Z");
}
}