use std::future::Future;
use std::sync::{Arc, Mutex};
use chrono::{DateTime, NaiveDate, NaiveDateTime, TimeDelta, TimeZone, Utc};
use chrono_tz::Tz;
tokio::task_local! {
static CLOCK: Arc<Mutex<Option<DateTime<Utc>>>>;
}
pub fn now() -> DateTime<Utc> {
CLOCK
.try_with(|clock| *clock.lock().unwrap_or_else(|e| e.into_inner()))
.ok()
.flatten()
.unwrap_or_else(Utc::now)
}
pub fn today() -> NaiveDate {
now().date_naive()
}
#[doc(hidden)]
pub async fn with_test_clock<F: Future>(fut: F) -> F::Output {
CLOCK.scope(Arc::default(), fut).await
}
pub(crate) fn set_clock(at: Option<DateTime<Utc>>) -> bool {
use chrono::SubsecRound as _;
let at = at.map(|at| at.trunc_subsecs(6));
CLOCK
.try_with(|clock| *clock.lock().unwrap_or_else(|e| e.into_inner()) = at)
.is_ok()
}
pub trait Now {
fn now() -> Self;
}
impl Now for DateTime<Utc> {
fn now() -> Self {
now()
}
}
impl Now for NaiveDateTime {
fn now() -> Self {
now().naive_utc()
}
}
pub trait Today {
fn today() -> Self;
}
impl Today for NaiveDate {
fn today() -> Self {
today()
}
}
pub trait Durations {
fn seconds(self) -> TimeDelta;
fn minutes(self) -> TimeDelta;
fn hours(self) -> TimeDelta;
fn days(self) -> TimeDelta;
fn weeks(self) -> TimeDelta;
}
impl Durations for i64 {
fn seconds(self) -> TimeDelta {
TimeDelta::seconds(self)
}
fn minutes(self) -> TimeDelta {
TimeDelta::minutes(self)
}
fn hours(self) -> TimeDelta {
TimeDelta::hours(self)
}
fn days(self) -> TimeDelta {
TimeDelta::days(self)
}
fn weeks(self) -> TimeDelta {
TimeDelta::weeks(self)
}
}
pub trait Relative {
fn ago(self) -> DateTime<Utc>;
#[allow(clippy::wrong_self_convention)]
fn from_now(self) -> DateTime<Utc>;
}
impl Relative for TimeDelta {
fn ago(self) -> DateTime<Utc> {
now() - self
}
fn from_now(self) -> DateTime<Utc> {
now() + self
}
}
static ZONE: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
pub(crate) fn configure(config: &crate::Config) -> crate::Result<()> {
if let Some(zone) = config.get_opt::<String>("time_zone")? {
if zone.parse::<Tz>().is_err() {
return Err(crate::Error::internal(format!(
"time_zone `{zone}` isn't a time zone; use an IANA name such as \"Europe/London\""
)));
}
*ZONE.write().unwrap_or_else(|e| e.into_inner()) = Some(zone);
}
Ok(())
}
pub fn zone() -> String {
ZONE.read()
.unwrap_or_else(|e| e.into_inner())
.clone()
.unwrap_or_else(|| "UTC".to_owned())
}
pub fn format_local(at: DateTime<Utc>, format: &str) -> String {
format_in_zone(at, &zone(), format).unwrap_or_else(|| at.format(format).to_string())
}
pub fn parse_local(text: &str) -> Option<DateTime<Utc>> {
parse(text, &zone())
}
pub fn in_zone(at: DateTime<Utc>, zone: &str) -> Option<DateTime<Tz>> {
let zone: Tz = zone.parse().ok()?;
Some(at.with_timezone(&zone))
}
pub fn format_in_zone(at: DateTime<Utc>, zone: &str, format: &str) -> Option<String> {
in_zone(at, zone).map(|local| local.format(format).to_string())
}
pub fn format_naive_in_zone(at: NaiveDateTime, zone: &str, format: &str) -> Option<String> {
format_in_zone(at.and_utc(), zone, format)
}
pub fn parse_http_date(text: &str) -> Option<DateTime<Utc>> {
let text = text.trim();
let without_weekday = text.split_once(", ").map_or(text, |(_, rest)| rest);
DateTime::parse_from_rfc2822(without_weekday)
.or_else(|_| DateTime::parse_from_rfc2822(text))
.ok()
.map(|at| at.with_timezone(&Utc))
}
pub fn parse(text: &str, zone: &str) -> Option<DateTime<Utc>> {
let text = text.trim();
if let Ok(at) = DateTime::parse_from_rfc3339(text) {
return Some(at.with_timezone(&Utc));
}
let local = [
"%Y-%m-%dT%H:%M:%S%.f",
"%Y-%m-%d %H:%M:%S%.f",
"%Y-%m-%dT%H:%M",
"%Y-%m-%d %H:%M",
]
.iter()
.find_map(|format| NaiveDateTime::parse_from_str(text, format).ok())
.or_else(|| {
chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d")
.ok()
.and_then(|date| date.and_hms_opt(0, 0, 0))
});
match local {
Some(local) => local_to_utc(local, zone).map(|at| at.and_utc()),
None => parse_http_date(text),
}
}
pub fn local_to_utc(local: NaiveDateTime, zone: &str) -> Option<NaiveDateTime> {
let zone: Tz = zone.parse().ok()?;
zone.from_local_datetime(&local)
.earliest()
.map(|at| at.naive_utc())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn a_frozen_clock_keeps_whole_microseconds() {
with_test_clock(async {
let at = DateTime::parse_from_rfc3339("2026-10-05T12:32:14.175663533Z")
.unwrap()
.with_timezone(&Utc);
assert!(set_clock(Some(at)));
assert_eq!(now().to_rfc3339(), "2026-10-05T12:32:14.175663+00:00");
})
.await;
}
#[test]
fn parses_as_time_zone_parse() {
let at = |text: &str, zone: &str| parse(text, zone).map(|t| t.to_rfc3339());
let utc = Some("2026-10-05T00:00:00+00:00".to_owned());
assert_eq!(at("2026-10-05", "UTC"), utc);
assert_eq!(at(" 2026-10-05 ", "Etc/UTC"), utc);
assert_eq!(
at("2026-10-05", "Europe/London"),
Some("2026-10-04T23:00:00+00:00".to_owned()),
"midnight on the zone's clock"
);
assert_eq!(
at("2026-10-05T11:00:00Z", "Europe/London"),
Some("2026-10-05T11:00:00+00:00".to_owned()),
"an offset wins"
);
assert_eq!(
at("2026-10-05 11:30", "UTC"),
Some("2026-10-05T11:30:00+00:00".to_owned())
);
assert_eq!(
at("2026-10-05T11:30:15.250", "UTC"),
Some("2026-10-05T11:30:15.250+00:00".to_owned())
);
assert_eq!(at("garbage", "UTC"), None);
assert_eq!(at("2026-13-45", "UTC"), None);
}
#[test]
fn reads_http_dates_whatever_the_weekday() {
let at = parse_http_date("Mon, 01 Jan 2030 00:00:00 GMT").unwrap();
assert_eq!(
at.to_rfc3339(),
"2030-01-01T00:00:00+00:00",
"1 Jan 2030 is a Tuesday"
);
assert!(parse_http_date("not a date").is_none());
}
#[test]
fn stores_local_times_as_utc() {
let local = chrono::NaiveDate::from_ymd_opt(2026, 8, 3)
.unwrap()
.and_hms_opt(23, 59, 59)
.unwrap();
assert_eq!(
local_to_utc(local, "Europe/London").unwrap().to_string(),
"2026-08-03 22:59:59"
);
assert!(local_to_utc(local, "Nowhere/Else").is_none());
}
#[test]
fn shows_utc_times_on_local_clocks() {
let at = DateTime::parse_from_rfc3339("2026-08-03T19:24:07Z")
.unwrap()
.to_utc();
assert_eq!(
format_in_zone(at, "Europe/London", "%d-%b-%Y %H:%M").as_deref(),
Some("03-Aug-2026 20:24"),
"British Summer Time"
);
let winter = DateTime::parse_from_rfc3339("2026-01-05T23:30:00Z")
.unwrap()
.to_utc();
assert_eq!(
format_in_zone(winter, "Australia/Sydney", "%d/%m/%Y").as_deref(),
Some("06/01/2026")
);
assert_eq!(format_in_zone(at, "Nowhere/Special", "%Y"), None);
}
}