BlueGit

timfa posprint

Files

posprint / src / datetime.rs

datetime.rs

datetime.rs 5.0 KiB Download Raw
1//! Locale-aware date/time formatting for `@date` and `@time` directives.
2
3use std::os::raw::{c_char, c_int};
4
5use chrono::{Datelike, Local, Timelike};
6use libc::tm;
7
8use crate::dsl::TimeFormatSpec;
9
10#[cfg(unix)]
11use libc::LC_TIME;
12
13#[cfg(windows)]
14const LC_TIME: c_int = 5;
15
16extern "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`).
22pub fn format_date(format: Option<&str>) -> String {
23 format_date_at(format, Local::now())
24}
25
26/// Format the current local time.
27pub fn format_time(spec: TimeFormatSpec) -> String {
28 format_time_at(spec, Local::now())
29}
30
31pub 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
46pub 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
62fn 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(all(unix, target_os = "macos"))]
76 tm_zone: std::ptr::null_mut(),
77 #[cfg(all(unix, not(target_os = "macos")))]
78 tm_zone: std::ptr::null(),
79 }
80}
81
82fn apply_locale() {
83 unsafe {
84 setlocale(LC_TIME, b"\0".as_ptr().cast());
85 }
86}
87
88fn strftime_tm(fmt: &str, tm: &tm) -> String {
89 let mut buf = [0u8; 128];
90 let fmt = std::ffi::CString::new(fmt).unwrap_or_else(|_| std::ffi::CString::new("%x").unwrap());
91 let len = unsafe { strftime(buf.as_mut_ptr().cast(), buf.len(), fmt.as_ptr(), tm) };
92 if len == 0 {
93 return String::new();
94 }
95 String::from_utf8_lossy(&buf[..len]).into_owned()
96}
97
98/// Convert template tokens (`DD`, `YYYY`, `MMMM`, …) to `strftime` format.
99pub fn date_pattern_to_strftime(pattern: &str) -> String {
100 const TOKENS: &[(&str, &str)] = &[
101 ("MMMM", "%B"),
102 ("YYYY", "%Y"),
103 ("MMM", "%b"),
104 ("DD", "%d"),
105 ("MM", "%m"),
106 ("YY", "%y"),
107 ];
108
109 let mut out = String::with_capacity(pattern.len());
110 let mut i = 0;
111 while i < pattern.len() {
112 let mut matched = false;
113 for (token, replacement) in TOKENS {
114 if pattern[i..].starts_with(token) {
115 out.push_str(replacement);
116 i += token.len();
117 matched = true;
118 break;
119 }
120 }
121 if matched {
122 continue;
123 }
124 let ch = pattern[i..].chars().next().expect("byte index on char boundary");
125 if ch == '%' {
126 out.push_str("%%");
127 } else {
128 out.push(ch);
129 }
130 i += ch.len_utf8();
131 }
132 out
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138 use chrono::TimeZone;
139
140 fn sample_dt() -> chrono::DateTime<Local> {
141 Local
142 .with_ymd_and_hms(2026, 7, 15, 16, 3, 0)
143 .single()
144 .expect("valid sample datetime")
145 }
146
147 #[test]
148 fn maps_custom_date_tokens() {
149 assert_eq!(date_pattern_to_strftime("DD-YYYY-MM"), "%d-%Y-%m");
150 assert_eq!(date_pattern_to_strftime("MMMM DD"), "%B %d");
151 }
152
153 #[test]
154 fn formats_custom_date_pattern() {
155 let dt = sample_dt();
156 assert_eq!(format_date_at(Some("DD-YYYY-MM"), dt), "15-2026-07");
157 let named = format_date_at(Some("MMMM DD"), dt);
158 assert!(named.contains("15"));
159 }
160
161 #[test]
162 fn formats_time_24h_and_12h() {
163 let dt = sample_dt();
164 assert_eq!(format_time_at(TimeFormatSpec::Hours24, dt), "16:03");
165 assert_eq!(format_time_at(TimeFormatSpec::Hours12, dt), "04:03 PM");
166 }
167
168 #[test]
169 fn regional_date_is_non_empty() {
170 let dt = sample_dt();
171 let formatted = format_date_at(None, dt);
172 assert!(!formatted.is_empty());
173 }
174}