#![forbid(unsafe_code)]
use std::time::{SystemTime, UNIX_EPOCH};
#[must_use]
pub fn now_unix_millis() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64)
}
#[must_use]
pub fn now_unix_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
#[must_use]
pub fn now_rfc3339() -> String {
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn millis_and_secs_agree() {
let secs = i64::try_from(now_unix_secs()).expect("unix seconds fit i64");
let millis = now_unix_millis();
assert!(
(millis - secs * 1000).abs() <= 1500,
"millis {millis} vs secs {secs} disagree by more than a second"
);
}
#[test]
fn millis_is_thirteen_digits_this_era() {
let millis = now_unix_millis();
assert!(
(1_000_000_000_000..=9_999_999_999_999).contains(&millis),
"millis outside the 13-digit era: {millis}"
);
}
#[test]
fn rfc3339_shape_is_z_terminated() {
let ts = now_rfc3339();
assert!(ts.ends_with('Z'), "got: {ts}");
assert_eq!(ts.len(), 20, "second-precision Z format, got: {ts}");
assert!(chrono::DateTime::parse_from_rfc3339(&ts).is_ok());
}
}