| 1 | //! Locale-aware date/time formatting for `@date` and `@time` directives.
|
| 2 |
|
| 3 | use std::os::raw::{c_char, c_int};
|
| 4 |
|
| 5 | use chrono::{Datelike, Local, Timelike};
|
| 6 | use libc::tm;
|
| 7 |
|
| 8 | use crate::dsl::TimeFormatSpec;
|
| 9 |
|
| 10 | #[cfg(unix)]
|
| 11 | use libc::LC_TIME;
|
| 12 |
|
| 13 | #[cfg(windows)]
|
| 14 | const LC_TIME: c_int = 5;
|
| 15 |
|
| 16 | extern "C" {
|
| 17 | fn strftime(s: *mut c_char, max: usize, format: *const c_char, tm: *const tm) -> usize;
|
| 18 | fn setlocale(category: c_int, locale: *const c_char) -> *mut c_char;
|
| 19 | }
|
| 20 |
|
| 21 | /// Format the current local date. `None` uses the system regional short date (`%x`).
|
| 22 | pub fn format_date(format: Option<&str>) -> String {
|
| 23 | format_date_at(format, Local::now())
|
| 24 | }
|
| 25 |
|
| 26 | /// Format the current local time.
|
| 27 | pub fn format_time(spec: TimeFormatSpec) -> String {
|
| 28 | format_time_at(spec, Local::now())
|
| 29 | }
|
| 30 |
|
| 31 | pub fn format_date_at(
|
| 32 | format: Option<&str>,
|
| 33 | at: chrono::DateTime<Local>,
|
| 34 | ) -> String {
|
| 35 | let tm = datetime_to_tm(&at);
|
| 36 | apply_locale();
|
| 37 | match format {
|
| 38 | None => strftime_tm("%x", &tm),
|
| 39 | Some(pattern) => {
|
| 40 | let strftime_fmt = date_pattern_to_strftime(pattern);
|
| 41 | strftime_tm(&strftime_fmt, &tm)
|
| 42 | }
|
| 43 | }
|
| 44 | }
|
| 45 |
|
| 46 | pub fn format_time_at(spec: TimeFormatSpec, at: chrono::DateTime<Local>) -> String {
|
| 47 | match spec {
|
| 48 | TimeFormatSpec::Hours24 => format!("{:02}:{:02}", at.hour(), at.minute()),
|
| 49 | TimeFormatSpec::Hours12 => {
|
| 50 | let hour = at.hour();
|
| 51 | let (hour12, ampm) = match hour {
|
| 52 | 0 => (12, "AM"),
|
| 53 | 1..=11 => (hour, "AM"),
|
| 54 | 12 => (12, "PM"),
|
| 55 | _ => (hour - 12, "PM"),
|
| 56 | };
|
| 57 | format!("{:02}:{:02} {ampm}", hour12, at.minute())
|
| 58 | }
|
| 59 | }
|
| 60 | }
|
| 61 |
|
| 62 | fn datetime_to_tm(dt: &chrono::DateTime<Local>) -> tm {
|
| 63 | tm {
|
| 64 | tm_sec: dt.second() as i32,
|
| 65 | tm_min: dt.minute() as i32,
|
| 66 | tm_hour: dt.hour() as i32,
|
| 67 | tm_mday: dt.day() as i32,
|
| 68 | tm_mon: (dt.month() - 1) as i32,
|
| 69 | tm_year: (dt.year() - 1900) as i32,
|
| 70 | tm_wday: dt.weekday().num_days_from_sunday() as i32,
|
| 71 | tm_yday: 0,
|
| 72 | tm_isdst: -1,
|
| 73 | #[cfg(unix)]
|
| 74 | tm_gmtoff: dt.offset().local_minus_utc() as libc::c_long,
|
| 75 | #[cfg(unix)]
|
| 76 | tm_zone: std::ptr::null(),
|
| 77 | }
|
| 78 | }
|
| 79 |
|
| 80 | fn apply_locale() {
|
| 81 | unsafe {
|
| 82 | setlocale(LC_TIME, b"\0".as_ptr().cast());
|
| 83 | }
|
| 84 | }
|
| 85 |
|
| 86 | fn strftime_tm(fmt: &str, tm: &tm) -> String {
|
| 87 | let mut buf = [0u8; 128];
|
| 88 | let fmt = std::ffi::CString::new(fmt).unwrap_or_else(|_| std::ffi::CString::new("%x").unwrap());
|
| 89 | let len = unsafe { strftime(buf.as_mut_ptr().cast(), buf.len(), fmt.as_ptr(), tm) };
|
| 90 | if len == 0 {
|
| 91 | return String::new();
|
| 92 | }
|
| 93 | String::from_utf8_lossy(&buf[..len]).into_owned()
|
| 94 | }
|
| 95 |
|
| 96 | /// Convert template tokens (`DD`, `YYYY`, `MMMM`, …) to `strftime` format.
|
| 97 | pub fn date_pattern_to_strftime(pattern: &str) -> String {
|
| 98 | const TOKENS: &[(&str, &str)] = &[
|
| 99 | ("MMMM", "%B"),
|
| 100 | ("YYYY", "%Y"),
|
| 101 | ("MMM", "%b"),
|
| 102 | ("DD", "%d"),
|
| 103 | ("MM", "%m"),
|
| 104 | ("YY", "%y"),
|
| 105 | ];
|
| 106 |
|
| 107 | let mut out = String::with_capacity(pattern.len());
|
| 108 | let mut i = 0;
|
| 109 | while i < pattern.len() {
|
| 110 | let mut matched = false;
|
| 111 | for (token, replacement) in TOKENS {
|
| 112 | if pattern[i..].starts_with(token) {
|
| 113 | out.push_str(replacement);
|
| 114 | i += token.len();
|
| 115 | matched = true;
|
| 116 | break;
|
| 117 | }
|
| 118 | }
|
| 119 | if matched {
|
| 120 | continue;
|
| 121 | }
|
| 122 | let ch = pattern[i..].chars().next().expect("byte index on char boundary");
|
| 123 | if ch == '%' {
|
| 124 | out.push_str("%%");
|
| 125 | } else {
|
| 126 | out.push(ch);
|
| 127 | }
|
| 128 | i += ch.len_utf8();
|
| 129 | }
|
| 130 | out
|
| 131 | }
|
| 132 |
|
| 133 | #[cfg(test)]
|
| 134 | mod tests {
|
| 135 | use super::*;
|
| 136 | use chrono::TimeZone;
|
| 137 |
|
| 138 | fn sample_dt() -> chrono::DateTime<Local> {
|
| 139 | Local
|
| 140 | .with_ymd_and_hms(2026, 7, 15, 16, 3, 0)
|
| 141 | .single()
|
| 142 | .expect("valid sample datetime")
|
| 143 | }
|
| 144 |
|
| 145 | #[test]
|
| 146 | fn maps_custom_date_tokens() {
|
| 147 | assert_eq!(date_pattern_to_strftime("DD-YYYY-MM"), "%d-%Y-%m");
|
| 148 | assert_eq!(date_pattern_to_strftime("MMMM DD"), "%B %d");
|
| 149 | }
|
| 150 |
|
| 151 | #[test]
|
| 152 | fn formats_custom_date_pattern() {
|
| 153 | let dt = sample_dt();
|
| 154 | assert_eq!(format_date_at(Some("DD-YYYY-MM"), dt), "15-2026-07");
|
| 155 | let named = format_date_at(Some("MMMM DD"), dt);
|
| 156 | assert!(named.contains("15"));
|
| 157 | }
|
| 158 |
|
| 159 | #[test]
|
| 160 | fn formats_time_24h_and_12h() {
|
| 161 | let dt = sample_dt();
|
| 162 | assert_eq!(format_time_at(TimeFormatSpec::Hours24, dt), "16:03");
|
| 163 | assert_eq!(format_time_at(TimeFormatSpec::Hours12, dt), "04:03 PM");
|
| 164 | }
|
| 165 |
|
| 166 | #[test]
|
| 167 | fn regional_date_is_non_empty() {
|
| 168 | let dt = sample_dt();
|
| 169 | let formatted = format_date_at(None, dt);
|
| 170 | assert!(!formatted.is_empty());
|
| 171 | }
|
| 172 | }
|