//! Locale-aware date/time formatting for `@date` and `@time` directives. use std::os::raw::{c_char, c_int}; use chrono::{Datelike, Local, Timelike}; use libc::tm; use crate::dsl::TimeFormatSpec; #[cfg(unix)] use libc::LC_TIME; #[cfg(windows)] const LC_TIME: c_int = 5; extern "C" { fn strftime(s: *mut c_char, max: usize, format: *const c_char, tm: *const tm) -> usize; fn setlocale(category: c_int, locale: *const c_char) -> *mut c_char; } /// Format the current local date. `None` uses the system regional short date (`%x`). pub fn format_date(format: Option<&str>) -> String { format_date_at(format, Local::now()) } /// Format the current local time. pub fn format_time(spec: TimeFormatSpec) -> String { format_time_at(spec, Local::now()) } pub fn format_date_at( format: Option<&str>, at: chrono::DateTime, ) -> String { let tm = datetime_to_tm(&at); apply_locale(); match format { None => strftime_tm("%x", &tm), Some(pattern) => { let strftime_fmt = date_pattern_to_strftime(pattern); strftime_tm(&strftime_fmt, &tm) } } } pub fn format_time_at(spec: TimeFormatSpec, at: chrono::DateTime) -> String { match spec { TimeFormatSpec::Hours24 => format!("{:02}:{:02}", at.hour(), at.minute()), TimeFormatSpec::Hours12 => { let hour = at.hour(); let (hour12, ampm) = match hour { 0 => (12, "AM"), 1..=11 => (hour, "AM"), 12 => (12, "PM"), _ => (hour - 12, "PM"), }; format!("{:02}:{:02} {ampm}", hour12, at.minute()) } } } fn datetime_to_tm(dt: &chrono::DateTime) -> tm { tm { tm_sec: dt.second() as i32, tm_min: dt.minute() as i32, tm_hour: dt.hour() as i32, tm_mday: dt.day() as i32, tm_mon: (dt.month() - 1) as i32, tm_year: (dt.year() - 1900) as i32, tm_wday: dt.weekday().num_days_from_sunday() as i32, tm_yday: 0, tm_isdst: -1, #[cfg(unix)] tm_gmtoff: dt.offset().local_minus_utc() as libc::c_long, #[cfg(all(unix, target_os = "macos"))] tm_zone: std::ptr::null_mut(), #[cfg(all(unix, not(target_os = "macos")))] tm_zone: std::ptr::null(), } } fn apply_locale() { unsafe { setlocale(LC_TIME, b"\0".as_ptr().cast()); } } fn strftime_tm(fmt: &str, tm: &tm) -> String { let mut buf = [0u8; 128]; let fmt = std::ffi::CString::new(fmt).unwrap_or_else(|_| std::ffi::CString::new("%x").unwrap()); let len = unsafe { strftime(buf.as_mut_ptr().cast(), buf.len(), fmt.as_ptr(), tm) }; if len == 0 { return String::new(); } String::from_utf8_lossy(&buf[..len]).into_owned() } /// Convert template tokens (`DD`, `YYYY`, `MMMM`, …) to `strftime` format. pub fn date_pattern_to_strftime(pattern: &str) -> String { const TOKENS: &[(&str, &str)] = &[ ("MMMM", "%B"), ("YYYY", "%Y"), ("MMM", "%b"), ("DD", "%d"), ("MM", "%m"), ("YY", "%y"), ]; let mut out = String::with_capacity(pattern.len()); let mut i = 0; while i < pattern.len() { let mut matched = false; for (token, replacement) in TOKENS { if pattern[i..].starts_with(token) { out.push_str(replacement); i += token.len(); matched = true; break; } } if matched { continue; } let ch = pattern[i..].chars().next().expect("byte index on char boundary"); if ch == '%' { out.push_str("%%"); } else { out.push(ch); } i += ch.len_utf8(); } out } #[cfg(test)] mod tests { use super::*; use chrono::TimeZone; fn sample_dt() -> chrono::DateTime { Local .with_ymd_and_hms(2026, 7, 15, 16, 3, 0) .single() .expect("valid sample datetime") } #[test] fn maps_custom_date_tokens() { assert_eq!(date_pattern_to_strftime("DD-YYYY-MM"), "%d-%Y-%m"); assert_eq!(date_pattern_to_strftime("MMMM DD"), "%B %d"); } #[test] fn formats_custom_date_pattern() { let dt = sample_dt(); assert_eq!(format_date_at(Some("DD-YYYY-MM"), dt), "15-2026-07"); let named = format_date_at(Some("MMMM DD"), dt); assert!(named.contains("15")); } #[test] fn formats_time_24h_and_12h() { let dt = sample_dt(); assert_eq!(format_time_at(TimeFormatSpec::Hours24, dt), "16:03"); assert_eq!(format_time_at(TimeFormatSpec::Hours12, dt), "04:03 PM"); } #[test] fn regional_date_is_non_empty() { let dt = sample_dt(); let formatted = format_date_at(None, dt); assert!(!formatted.is_empty()); } }