use std::fmt::Write as _;
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) fn write_rfc3339_micros(out: &mut String, at: SystemTime) {
let since = at.duration_since(UNIX_EPOCH).unwrap_or_default();
let seconds = since.as_secs();
let micros = since.subsec_micros();
let (year, month, day) = civil_from_days((seconds / 86_400) as i64);
let remainder = seconds % 86_400;
let _ = write!(
out,
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{micros:06}Z",
remainder / 3600,
(remainder % 3600) / 60,
remainder % 60
);
}
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let day_of_era = z - era * 146_097;
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let year = year_of_era + era * 400;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_index = (5 * day_of_year + 2) / 153;
let day = (day_of_year - (153 * month_index + 2) / 5 + 1) as u32;
let month = if month_index < 10 {
month_index + 3
} else {
month_index - 9
} as u32;
(if month <= 2 { year + 1 } else { year }, month, day)
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
fn at(seconds: u64, micros: u32) -> String {
let mut out = String::new();
write_rfc3339_micros(
&mut out,
UNIX_EPOCH + Duration::from_secs(seconds) + Duration::from_micros(micros as u64),
);
out
}
#[test]
fn formats_the_epoch_leap_days_and_century_rules() {
assert_eq!(at(0, 0), "1970-01-01T00:00:00.000000Z");
assert_eq!(at(951_782_400, 0), "2000-02-29T00:00:00.000000Z");
assert_eq!(at(4_107_542_399, 0), "2100-02-28T23:59:59.000000Z");
assert_eq!(
at(1_758_412_800 + 3_661, 991_167),
"2025-09-21T01:01:01.991167Z"
);
}
#[test]
fn a_clock_before_the_epoch_does_not_panic() {
let mut out = String::new();
write_rfc3339_micros(&mut out, UNIX_EPOCH - Duration::from_secs(60));
assert_eq!(out, "1970-01-01T00:00:00.000000Z");
}
}