BlueGit

timfa posprint

Files

posprint / src / datetime.rs

datetime.rs

fixes
timfa Tim Falken · pushed by timfa · 4 months ago
4ab2186f History
datetime.rs 4.7 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 }
74}
75
76fn apply_locale() {
77 unsafe {
78 setlocale(LC_TIME, b"\0".as_ptr().cast());
79 }
80}
81
82fn strftime_tm(fmt: &str, tm: &tm) -> String {
83 let mut buf = [0u8; 128];
84 let fmt = std::ffi::CString::new(fmt).unwrap_or_else(|_| std::ffi::CString::new("%x").unwrap());
85 let len = unsafe { strftime(buf.as_mut_ptr().cast(), buf.len(), fmt.as_ptr(), tm) };
86 if len == 0 {
87 return String::new();
88 }
89 String::from_utf8_lossy(&buf[..len]).into_owned()
90}
91
92/// Convert template tokens (`DD`, `YYYY`, `MMMM`, …) to `strftime` format.
93pub fn date_pattern_to_strftime(pattern: &str) -> String {
94 const TOKENS: &[(&str, &str)] = &[
95 ("MMMM", "%B"),
96 ("YYYY", "%Y"),
97 ("MMM", "%b"),
98 ("DD", "%d"),
99 ("MM", "%m"),
100 ("YY", "%y"),
101 ];
102
103 let mut out = String::with_capacity(pattern.len());
104 let mut i = 0;
105 while i < pattern.len() {
106 let mut matched = false;
107 for (token, replacement) in TOKENS {
108 if pattern[i..].starts_with(token) {
109 out.push_str(replacement);
110 i += token.len();
111 matched = true;
112 break;
113 }
114 }
115 if matched {
116 continue;
117 }
118 let ch = pattern[i..].chars().next().expect("byte index on char boundary");
119 if ch == '%' {
120 out.push_str("%%");
121 } else {
122 out.push(ch);
123 }
124 i += ch.len_utf8();
125 }
126 out
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132 use chrono::TimeZone;
133
134 fn sample_dt() -> chrono::DateTime<Local> {
135 Local
136 .with_ymd_and_hms(2026, 7, 15, 16, 3, 0)
137 .single()
138 .expect("valid sample datetime")
139 }
140
141 #[test]
142 fn maps_custom_date_tokens() {
143 assert_eq!(date_pattern_to_strftime("DD-YYYY-MM"), "%d-%Y-%m");
144 assert_eq!(date_pattern_to_strftime("MMMM DD"), "%B %d");
145 }
146
147 #[test]
148 fn formats_custom_date_pattern() {
149 let dt = sample_dt();
150 assert_eq!(format_date_at(Some("DD-YYYY-MM"), dt), "15-2026-07");
151 let named = format_date_at(Some("MMMM DD"), dt);
152 assert!(named.contains("15"));
153 }
154
155 #[test]
156 fn formats_time_24h_and_12h() {
157 let dt = sample_dt();
158 assert_eq!(format_time_at(TimeFormatSpec::Hours24, dt), "16:03");
159 assert_eq!(format_time_at(TimeFormatSpec::Hours12, dt), "04:03 PM");
160 }
161
162 #[test]
163 fn regional_date_is_non_empty() {
164 let dt = sample_dt();
165 let formatted = format_date_at(None, dt);
166 assert!(!formatted.is_empty());
167 }
168}