use std::cell::RefCell;
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn unix_millis() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
#[cfg(not(test))]
fn now_secs() -> u64 {
unix_millis() / 1000
}
#[cfg(test)]
fn now_secs() -> u64 {
TICKING.with(|t| match t.get() {
Some(secs) => {
t.set(Some(secs + 1));
secs
}
None => unix_millis() / 1000,
})
}
#[cfg(test)]
thread_local! {
static TICKING: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
pub struct Ticking;
#[cfg(test)]
impl Ticking {
pub fn start(secs: u64) -> Ticking {
TICKING.with(|t| t.set(Some(secs)));
Ticking
}
}
#[cfg(test)]
impl Drop for Ticking {
fn drop(&mut self) {
TICKING.with(|t| t.set(None));
}
}
pub fn now_rfc3339() -> String {
let secs = now_secs();
let (y, m, d) = civil_from_days((secs / 86_400) as i64);
let rem = secs % 86_400;
format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
y,
m,
d,
rem / 3600,
(rem % 3600) / 60,
rem % 60
)
}
pub fn date_of(ts: &str) -> String {
match local_ymd(ts) {
Some((y, m, d)) => format!("{y:04}-{m:02}-{d:02}"),
None => ts.chars().take(10).collect(),
}
}
pub fn days_between(from: &str, to: &str) -> Option<i64> {
Some(days_from_civil(local_ymd(to)?) - days_from_civil(local_ymd(from)?))
}
fn local_ymd(ts: &str) -> Option<(i64, u32, u32)> {
match epoch_seconds(ts) {
Some(secs) => Some(local_date_from(secs, local_offset_secs(secs))),
None => parse_date(ts),
}
}
fn parse_date(ts: &str) -> Option<(i64, u32, u32)> {
let b = ts.as_bytes();
if b.len() < 10 || b[4] != b'-' || b[7] != b'-' {
return None;
}
Some((
ts[0..4].parse().ok()?,
ts[5..7].parse().ok()?,
ts[8..10].parse().ok()?,
))
}
pub fn epoch_seconds(ts: &str) -> Option<i64> {
let b = ts.as_bytes();
if b.len() != 20
|| b[4] != b'-'
|| b[7] != b'-'
|| b[10] != b'T'
|| b[13] != b':'
|| b[16] != b':'
|| b[19] != b'Z'
{
return None;
}
let y: i64 = ts[0..4].parse().ok()?;
let m: u32 = ts[5..7].parse().ok()?;
let d: u32 = ts[8..10].parse().ok()?;
let hh: i64 = ts[11..13].parse().ok()?;
let mm: i64 = ts[14..16].parse().ok()?;
let ss: i64 = ts[17..19].parse().ok()?;
Some(days_from_civil((y, m, d)) * 86_400 + hh * 3600 + mm * 60 + ss)
}
fn days_from_civil((y, m, d): (i64, u32, u32)) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = if m > 2 { m - 3 } else { m + 9 } as i64;
let doy = (153 * mp + 2) / 5 + d as i64 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
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;
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)
}
fn local_date_from(secs: i64, offset_secs: i64) -> (i64, u32, u32) {
civil_from_days((secs + offset_secs).div_euclid(86_400))
}
thread_local! {
static OFFSET_SECS_CACHE: RefCell<HashMap<i64, i64>> = RefCell::new(HashMap::new());
}
fn local_offset_secs(secs: i64) -> i64 {
let bucket = secs.div_euclid(900);
let cached = OFFSET_SECS_CACHE.with(|c| c.borrow().get(&bucket).copied());
match cached {
Some(v) => v,
None => {
let v = os_offset_secs(secs);
OFFSET_SECS_CACHE.with(|c| c.borrow_mut().insert(bucket, v));
v
}
}
}
#[cfg(all(not(test), windows))]
fn os_offset_secs(secs: i64) -> i64 {
windows_zone::offset_secs(secs)
}
#[cfg(all(not(test), unix))]
fn os_offset_secs(secs: i64) -> i64 {
unix_zone::offset_secs(secs)
}
#[cfg(all(not(test), not(any(windows, unix))))]
fn os_offset_secs(_secs: i64) -> i64 {
0
}
#[cfg(test)]
fn os_offset_secs(_secs: i64) -> i64 {
0
}
#[cfg(all(not(test), windows))]
mod windows_zone {
use std::ffi::c_void;
#[repr(C)]
#[allow(dead_code)]
struct SystemTime {
year: u16,
month: u16,
day_of_week: u16,
day: u16,
hour: u16,
minute: u16,
second: u16,
milliseconds: u16,
}
#[link(name = "kernel32")]
extern "system" {
fn SystemTimeToTzSpecificLocalTime(
zone: *const c_void,
utc: *const SystemTime,
local: *mut SystemTime,
) -> i32;
}
fn is_utc_spelling(tz: &str) -> bool {
matches!(tz, "UTC" | "UTC0" | "GMT" | "GMT0")
}
pub(super) fn offset_secs(secs: i64) -> i64 {
if std::env::var("TZ")
.ok()
.is_some_and(|tz| is_utc_spelling(&tz))
{
return 0;
}
let utc_days = secs.div_euclid(86_400);
let (y, m, d) = super::civil_from_days(utc_days);
let rem = secs - utc_days * 86_400;
let utc = SystemTime {
year: y as u16,
month: m as u16,
day_of_week: 0,
day: d as u16,
hour: (rem / 3600) as u16,
minute: ((rem % 3600) / 60) as u16,
second: (rem % 60) as u16,
milliseconds: 0,
};
let mut local = SystemTime {
year: 0,
month: 0,
day_of_week: 0,
day: 0,
hour: 0,
minute: 0,
second: 0,
milliseconds: 0,
};
let ok = unsafe { SystemTimeToTzSpecificLocalTime(std::ptr::null(), &utc, &mut local) };
if ok == 0 {
return 0;
}
let local_secs =
super::days_from_civil((local.year as i64, local.month as u32, local.day as u32))
* 86_400
+ local.hour as i64 * 3600
+ local.minute as i64 * 60
+ local.second as i64;
local_secs - secs
}
}
#[cfg(all(not(test), unix))]
mod unix_zone {
use std::os::raw::c_int;
#[repr(C)]
#[allow(dead_code)]
struct Tm {
sec: c_int,
min: c_int,
hour: c_int,
mday: c_int,
mon: c_int,
year: c_int,
_day_counters: [c_int; 3],
_reserved: [u64; 8],
}
extern "C" {
fn tzset();
fn localtime_r(time: *const i64, result: *mut Tm) -> *mut Tm;
}
pub(super) fn offset_secs(secs: i64) -> i64 {
let mut tm = Tm {
sec: 0,
min: 0,
hour: 0,
mday: 0,
mon: 0,
year: 0,
_day_counters: [0; 3],
_reserved: [0; 8],
};
let filled = unsafe {
tzset();
localtime_r(&secs, &mut tm)
};
if filled.is_null() {
return 0;
}
let local_secs =
super::days_from_civil((1900 + tm.year as i64, (tm.mon + 1) as u32, tm.mday as u32))
* 86_400
+ tm.hour as i64 * 3600
+ tm.min as i64 * 60
+ tm.sec as i64;
local_secs - secs
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_day_apart_is_one_day() {
assert_eq!(
days_between("2026-09-07T23:59:00Z", "2026-09-08T00:01:00Z"),
Some(1)
);
}
#[test]
fn the_same_day_is_zero_however_many_hours_apart() {
assert_eq!(
days_between("2026-09-08T00:01:00Z", "2026-09-08T23:59:00Z"),
Some(0)
);
}
#[test]
fn a_month_boundary_counts_the_real_days() {
assert_eq!(
days_between("2026-02-27T00:00:00Z", "2026-03-01T00:00:00Z"),
Some(2)
);
}
#[test]
fn a_leap_day_counts() {
assert_eq!(
days_between("2024-02-28T00:00:00Z", "2024-03-01T00:00:00Z"),
Some(2)
);
}
#[test]
fn going_backwards_is_negative() {
assert_eq!(
days_between("2026-09-08T00:00:00Z", "2026-09-01T00:00:00Z"),
Some(-7)
);
}
#[test]
fn a_stamp_that_is_not_one_is_none() {
assert_eq!(days_between("yesterday", "2026-09-08T00:00:00Z"), None);
assert_eq!(days_between("2026-09-08T00:00:00Z", "2026-9-8"), None);
}
#[test]
fn epoch_is_1970() {
assert_eq!(civil_from_days(0), (1970, 1, 1));
}
#[test]
fn known_dates() {
assert_eq!(civil_from_days(20_696), (2026, 8, 31));
assert_eq!(civil_from_days(19_782), (2024, 2, 29));
assert_eq!(civil_from_days(-1), (1969, 12, 31));
}
#[test]
fn format_is_stable() {
let s = now_rfc3339();
assert_eq!(s.len(), 20);
assert!(s.ends_with('Z'));
}
#[test]
fn epoch_seconds_reads_the_epoch_itself() {
assert_eq!(epoch_seconds("1970-01-01T00:00:00Z"), Some(0));
}
#[test]
fn epoch_seconds_counts_the_time_of_day_too() {
assert_eq!(
epoch_seconds("1970-01-01T00:01:00Z"),
Some(60),
"a minute past the epoch is 60 seconds, not 0"
);
assert_eq!(
epoch_seconds("2026-09-08T12:00:00Z").unwrap()
- epoch_seconds("2026-09-08T00:00:00Z").unwrap(),
43_200,
"noon is half a day past midnight on the same date"
);
}
#[test]
fn epoch_seconds_of_a_bare_date_is_none() {
assert_eq!(epoch_seconds("2026-09-08"), None);
}
#[test]
fn epoch_seconds_of_garbage_is_none() {
assert_eq!(epoch_seconds("not a timestamp"), None);
}
#[test]
fn date_of_reads_the_date_of_a_full_stamp() {
assert_eq!(date_of("2026-09-08T23:30:00Z"), "2026-09-08");
}
#[test]
fn date_of_of_a_bare_date_is_unchanged() {
assert_eq!(date_of("2026-09-08"), "2026-09-08");
}
#[test]
fn date_of_of_garbage_is_the_first_ten_bytes() {
assert_eq!(date_of("not a timestamp"), "not a time");
}
#[test]
fn a_negative_offset_short_of_midnight_keeps_the_same_day() {
let secs = epoch_seconds("2026-09-08T23:30:00Z").unwrap();
assert_eq!(local_date_from(secs, -5 * 3600), (2026, 9, 8));
}
#[test]
fn a_negative_offset_past_midnight_falls_back_a_day() {
let secs = epoch_seconds("2026-09-08T02:00:00Z").unwrap();
assert_eq!(local_date_from(secs, -5 * 3600), (2026, 9, 7));
}
#[test]
fn a_negative_offset_crosses_a_month_boundary() {
let secs = epoch_seconds("2026-03-01T02:00:00Z").unwrap();
assert_eq!(local_date_from(secs, -5 * 3600), (2026, 2, 28));
}
#[test]
fn a_negative_offset_crosses_a_year_boundary() {
let secs = epoch_seconds("2026-01-01T02:00:00Z").unwrap();
assert_eq!(local_date_from(secs, -5 * 3600), (2025, 12, 31));
}
#[test]
fn a_positive_offset_crosses_into_the_next_day() {
let secs = epoch_seconds("2026-09-08T22:00:00Z").unwrap();
assert_eq!(local_date_from(secs, 5 * 3600), (2026, 9, 9));
}
#[test]
fn india_fractional_offset_keeps_the_same_day_short_of_its_own_midnight() {
let secs = epoch_seconds("2026-09-08T18:25:00Z").unwrap();
assert_eq!(local_date_from(secs, 19_800), (2026, 9, 8));
}
#[test]
fn india_fractional_offset_crosses_at_its_own_midnight() {
let secs = epoch_seconds("2026-09-08T18:35:00Z").unwrap();
assert_eq!(local_date_from(secs, 19_800), (2026, 9, 9));
}
#[test]
fn nepal_fractional_offset_keeps_the_same_day_short_of_its_own_midnight() {
let secs = epoch_seconds("2026-09-08T18:10:00Z").unwrap();
assert_eq!(local_date_from(secs, 20_700), (2026, 9, 8));
}
#[test]
fn nepal_fractional_offset_crosses_at_its_own_midnight() {
let secs = epoch_seconds("2026-09-08T18:20:00Z").unwrap();
assert_eq!(local_date_from(secs, 20_700), (2026, 9, 9));
}
}