1use std::fmt::Write as _;
5
6use crate::params::{
7 DAYS_PER_WEEK, FULL_NAME_LETTERS, HOURS_PER_DAY, HOURS_PER_HALF_DAY, LEAP_YEAR_CYCLES, MARCH,
8 MAX_DAY_OF_MONTH, MAX_SECONDS_PER_MINUTE, MINUTES_PER_HOUR, MONTH_DAYS, MONTHS_PER_YEAR,
9 SHORT_NAME_LETTERS, WEEKDAY_SHIFTS, YEAR_DIGITS, YEARS_PER_CENTURY,
10};
11
12const AM_PM: &str = "AM/PM";
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct DateTime {
18 pub year: i32,
20 pub month: u8,
22 pub day: u8,
24 pub hour: u8,
26 pub minute: u8,
28 pub second: u8,
30}
31
32const MONTHS: [&str; 12] = [
33 "January",
34 "February",
35 "March",
36 "April",
37 "May",
38 "June",
39 "July",
40 "August",
41 "September",
42 "October",
43 "November",
44 "December",
45];
46
47const DAYS: [&str; 7] = [
48 "Sunday",
49 "Monday",
50 "Tuesday",
51 "Wednesday",
52 "Thursday",
53 "Friday",
54 "Saturday",
55];
56
57fn month_of(word: &str) -> Option<u8> {
59 let word = word.trim_end_matches(['.', ',']).to_lowercase();
60 let index = MONTHS.iter().position(|name| {
61 let name = name.to_lowercase();
62 word == name || (word.len() == SHORT_NAME_LETTERS && name.starts_with(&word))
63 })?;
64 u8::try_from(index + 1).ok()
65}
66
67fn days_in_month(year: i32, month: u8) -> u8 {
70 let (leap, century, cycle) = LEAP_YEAR_CYCLES;
71 let is_leap = year.rem_euclid(leap) == 0
72 && (year.rem_euclid(century) != 0 || year.rem_euclid(cycle) == 0);
73 let days = usize::from(month)
74 .checked_sub(1)
75 .and_then(|index| MONTH_DAYS.get(index).copied())
76 .unwrap_or(MAX_DAY_OF_MONTH);
77 let leap_day = usize::from(month) + 1 == MARCH && is_leap;
78 days + u8::from(leap_day)
79}
80
81fn day_of(word: &str) -> Option<u8> {
83 word.trim_end_matches(',').parse().ok()
84}
85
86fn iso_date(text: &str) -> Option<(i32, u8, u8)> {
88 let mut parts = text.split('T').next()?.split('-');
89 let year = parts.next()?.parse().ok()?;
90 Some((
91 year,
92 parts.next()?.parse().ok()?,
93 parts.next()?.parse().ok()?,
94 ))
95}
96
97pub const DATE_PICTURE: &str = "M/d/yyyy";
99
100pub const TIME_PICTURE: &str = "h:mm AM/PM";
102
103pub const SAVED_DATE_PICTURE: &str = "M/d/yyyy h:mm:'00' AM/PM";
107
108pub const PROPERTY_DATE_PICTURE: &str = "d/M/yyyy";
111
112impl DateTime {
113 #[must_use]
117 pub fn local_date(self, zone_minutes: i32) -> Self {
118 let per_hour = i32::from(MINUTES_PER_HOUR);
119 let minutes = i32::from(self.hour) * per_hour + i32::from(self.minute);
120 let days = (minutes + zone_minutes).div_euclid(i32::from(HOURS_PER_DAY) * per_hour);
121 let mut date = Self {
122 hour: 0,
123 minute: 0,
124 second: 0,
125 ..self
126 };
127 for _ in 0..days.unsigned_abs() {
128 date = if days > 0 {
129 date.next_day()
130 } else {
131 date.day_before()
132 };
133 }
134 date
135 }
136
137 fn next_day(self) -> Self {
139 if self.day < days_in_month(self.year, self.month) {
140 Self {
141 day: self.day + 1,
142 ..self
143 }
144 } else if self.month < MONTHS_PER_YEAR {
145 Self {
146 month: self.month + 1,
147 day: 1,
148 ..self
149 }
150 } else {
151 Self {
152 year: self.year.saturating_add(1),
153 month: 1,
154 day: 1,
155 ..self
156 }
157 }
158 }
159
160 fn day_before(self) -> Self {
162 if self.day > 1 {
163 Self {
164 day: self.day - 1,
165 ..self
166 }
167 } else if self.month > 1 {
168 let month = self.month - 1;
169 Self {
170 month,
171 day: days_in_month(self.year, month),
172 ..self
173 }
174 } else {
175 let year = self.year.saturating_sub(1);
176 Self {
177 year,
178 month: MONTHS_PER_YEAR,
179 day: days_in_month(year, MONTHS_PER_YEAR),
180 ..self
181 }
182 }
183 }
184
185 #[must_use]
188 pub fn parse_utc(text: &str) -> Option<Self> {
189 let text = text.trim().strip_suffix('Z')?;
190 let (date, time) = text.split_once('T')?;
191 let mut date = date.split('-');
192 let mut time = time.split(':');
193 let next = |part: Option<&str>| part.and_then(|p| p.split('.').next()?.parse().ok());
194 let year: i32 = date.next()?.parse().ok()?;
195 let parsed = Self {
196 year,
197 month: next(date.next())?,
198 day: next(date.next())?,
199 hour: next(time.next())?,
200 minute: next(time.next())?,
201 second: next(time.next()).unwrap_or(0),
202 };
203 let valid = (1..=MONTHS_PER_YEAR).contains(&parsed.month)
204 && (1..=MAX_DAY_OF_MONTH).contains(&parsed.day)
205 && parsed.hour < HOURS_PER_DAY
206 && parsed.minute < MINUTES_PER_HOUR
207 && parsed.second < MAX_SECONDS_PER_MINUTE;
208 valid.then_some(parsed)
209 }
210
211 #[must_use]
214 pub fn parse_text(text: &str) -> Option<Self> {
215 let words: Vec<&str> = text.split_whitespace().collect();
216 let (year, month, day) = match words.as_slice() {
217 [d, m, y] if day_of(d).is_some() => (y.parse().ok()?, month_of(m)?, day_of(d)?),
218 [m, d, y] => (y.parse().ok()?, month_of(m)?, day_of(d)?),
219 [iso] => iso_date(iso)?,
220 _ => return None,
221 };
222 let valid = (1..=MONTHS_PER_YEAR).contains(&month) && (1..=MAX_DAY_OF_MONTH).contains(&day);
223 valid.then_some(Self {
224 year,
225 month,
226 day,
227 hour: 0,
228 minute: 0,
229 second: 0,
230 })
231 }
232
233 fn weekday(self) -> usize {
236 let month = usize::from(self.month.clamp(1, MONTHS_PER_YEAR));
240 let year = i64::from(self.year) - i64::from(month < MARCH);
241 let shift = i64::from(WEEKDAY_SHIFTS.get(month - 1).copied().unwrap_or(0));
242 let (leap, century, cycle) = LEAP_YEAR_CYCLES;
243 let years = |cycle: i32| year.div_euclid(i64::from(cycle));
244 let day = year + years(leap) - years(century) + years(cycle) + shift + i64::from(self.day);
245 usize::try_from(day.rem_euclid(i64::from(DAYS_PER_WEEK))).unwrap_or(0)
246 }
247
248 #[must_use]
254 pub fn write(self, picture: &str) -> String {
255 let chars: Vec<char> = picture.chars().collect();
256 let mut out = String::new();
257 let mut i = 0;
258 while let Some(&ch) = chars.get(i) {
259 let rest = chars.get(i..).unwrap_or_default();
260 let run = rest.iter().take_while(|&&c| c == ch).count();
261 let starts = |text: &str, lower: bool| {
262 let text = text
263 .chars()
264 .map(|c| if lower { c.to_ascii_lowercase() } else { c });
265 rest.iter().copied().take(AM_PM.len()).eq(text)
266 };
267 if ch == '\'' {
268 let end = chars
269 .get(i + 1..)
270 .and_then(|tail| tail.iter().position(|&c| c == '\''))
271 .map_or(chars.len(), |p| i + 1 + p);
272 out.extend(chars.get(i + 1..end).unwrap_or_default());
273 i = end + 1;
274 continue;
275 }
276 if starts(AM_PM, false) || starts(AM_PM, true) {
277 let pm = self.hour >= HOURS_PER_HALF_DAY;
278 let text = match (pm, ch == 'A') {
279 (true, true) => "PM",
280 (false, true) => "AM",
281 (true, false) => "pm",
282 (false, false) => "am",
283 };
284 out.push_str(text);
285 i += AM_PM.len();
286 continue;
287 }
288 let wrote = self.field(ch, run, &mut out);
289 if wrote {
290 i += run;
291 } else {
292 let kept = run.saturating_sub(1).max(1);
296 out.extend(std::iter::repeat_n(ch, kept));
297 i += kept;
298 }
299 }
300 out
301 }
302
303 fn field(self, ch: char, count: usize, out: &mut String) -> bool {
305 let number = |out: &mut String, value: u32, width: usize| {
306 let _ = write!(out, "{value:0width$}");
307 };
308 let name = |names: &[&str], index: usize, count: usize| {
309 let full = names.get(index).copied().unwrap_or("");
310 if count == SHORT_NAME_LETTERS {
311 full.chars().take(SHORT_NAME_LETTERS).collect()
312 } else {
313 full.to_owned()
314 }
315 };
316 let hour12 = match self.hour % HOURS_PER_HALF_DAY {
317 0 => HOURS_PER_HALF_DAY,
318 h => h,
319 };
320 match (ch, count) {
321 ('d', 1 | 2) => number(out, u32::from(self.day), count),
322 ('d', _) => out.push_str(&name(&DAYS, self.weekday(), count.min(FULL_NAME_LETTERS))),
323 ('M', 1 | 2) => number(out, u32::from(self.month), count),
324 ('M', _) => {
325 let index = usize::from(self.month.clamp(1, MONTHS_PER_YEAR)) - 1;
326 out.push_str(&name(&MONTHS, index, count.min(FULL_NAME_LETTERS)));
327 }
328 ('y', 1 | 2) => number(
329 out,
330 self.year.rem_euclid(YEARS_PER_CENTURY).unsigned_abs(),
331 2,
332 ),
333 ('y', _) => number(out, self.year.unsigned_abs(), YEAR_DIGITS),
334 ('h', _) => number(out, u32::from(hour12), count.min(2)),
335 ('H', _) => number(out, u32::from(self.hour), count.min(2)),
336 ('m', _) => number(out, u32::from(self.minute), count.min(2)),
337 ('s', _) => number(out, u32::from(self.second), count.min(2)),
338 _ => return false,
339 }
340 true
341 }
342}
343
344#[cfg(test)]
345mod tests {
346 use super::DateTime;
347
348 fn date(year: i32, month: u8, day: u8, hour: u8) -> DateTime {
349 DateTime {
350 year,
351 month,
352 day,
353 hour,
354 minute: 0,
355 second: 0,
356 }
357 }
358
359 #[test]
360 fn reads_times_of_date_properties() {
361 let utc = DateTime::parse_utc("2018-12-28T13:00:00Z");
362 assert_eq!(utc, Some(date(2018, 12, 28, 13)));
363 assert_eq!(DateTime::parse_utc("2018-12-28"), None);
364 assert_eq!(DateTime::parse_utc("2018-13-28T13:00:00Z"), None);
365 }
366
367 #[test]
368 fn takes_the_date_of_a_utc_time_in_a_zone_at_midnight() {
369 let at = |year, month, day, hour, minute| DateTime {
370 year,
371 month,
372 day,
373 hour,
374 minute,
375 second: 30,
376 };
377 let day = |year, month, day| date(year, month, day, 0);
378 let cases = [
379 (at(2026, 1, 15, 3, 30), 480, day(2026, 1, 15)),
381 (at(2026, 7, 15, 3, 30), 480, day(2026, 7, 15)),
382 (at(2026, 1, 15, 23, 30), 480, day(2026, 1, 16)),
383 (at(2026, 12, 31, 20, 0), 480, day(2027, 1, 1)),
385 (at(2024, 2, 28, 16, 0), 480, day(2024, 2, 29)),
386 (at(2023, 2, 28, 16, 0), 480, day(2023, 3, 1)),
387 (at(1900, 2, 28, 16, 0), 480, day(1900, 3, 1)),
388 (at(2000, 2, 28, 16, 0), 480, day(2000, 2, 29)),
389 (at(2026, 4, 30, 15, 59), 480, day(2026, 4, 30)),
390 (at(2026, 3, 1, 2, 0), -300, day(2026, 2, 28)),
392 (at(2024, 3, 1, 2, 0), -300, day(2024, 2, 29)),
393 (at(2026, 1, 1, 1, 0), -300, day(2025, 12, 31)),
394 (at(2026, 5, 1, 4, 59), -300, day(2026, 4, 30)),
395 (at(2026, 5, 1, 5, 0), -300, day(2026, 5, 1)),
396 (at(2026, 1, 15, 23, 59), 0, day(2026, 1, 15)),
398 ];
399 for (utc, zone, local) in cases {
400 assert_eq!(utc.local_date(zone), local, "{utc:?} {zone}");
401 }
402 assert_eq!(
403 day(2026, 1, 15)
404 .local_date(480)
405 .write(super::PROPERTY_DATE_PICTURE),
406 "15/1/2026"
407 );
408 }
409
410 #[test]
411 fn reads_dates_written_as_text() {
412 for text in [
413 "20 April 2023",
414 "20 Apr 2023",
415 "April 20, 2023",
416 "2023-04-20",
417 ] {
418 assert_eq!(
419 DateTime::parse_text(text),
420 Some(date(2023, 4, 20, 0)),
421 "{text}"
422 );
423 }
424 for text in ["Unknown", "20 Avril 2023", "32 April 2023", "April"] {
425 assert_eq!(DateTime::parse_text(text), None, "{text}");
426 }
427 assert_eq!(date(2023, 4, 20, 0).write("dd/MM/yyyy"), "20/04/2023");
428 }
429
430 const PRINTED: DateTime = DateTime {
431 year: 2026,
432 month: 9,
433 day: 25,
434 hour: 14,
435 minute: 33,
436 second: 2,
437 };
438
439 #[test]
440 fn writes_dates_and_times_with_pictures() {
441 let cases = [
442 ("dddd, MMMM d, yyyy", "Friday, September 25, 2026"),
443 ("d MMMM yyyy", "25 September 2026"),
444 ("yyyy", "2026"),
445 ("M/d/yyyy", "9/25/2026"),
446 ("dd/MM/yy", "25/09/26"),
447 ("ddd d MMM", "Fri 25 Sep"),
448 ("dd/MM/yyyy H:mm:ss", "25/09/2026 14:33:02"),
449 ("d/M/yyyy h:mm AM/PM", "25/9/2026 2:33 PM"),
450 ("h:mm am/pm", "2:33 pm"),
451 ("'Week of' d MMMM", "Week of 25 September"),
452 ("d.M.yyyy", "25.9.2026"),
453 ("xxAAAM/PM zz", "xxAAPM zz"),
455 ("aaam/pm aAM/PM", "aapm aPM"),
456 ("AAM/P", "AA9/P"),
457 (super::SAVED_DATE_PICTURE, "9/25/2026 2:33:00 PM"),
459 ];
460 for (picture, text) in cases {
461 assert_eq!(PRINTED.write(picture), text, "{picture}");
462 }
463 }
464
465 #[test]
466 fn finds_the_day_of_the_week() {
467 let day = |year, month, day| DateTime {
468 year,
469 month,
470 day,
471 hour: 0,
472 minute: 0,
473 second: 0,
474 };
475 assert_eq!(day(2026, 9, 25).write("dddd"), "Friday");
476 assert_eq!(day(2000, 1, 1).write("dddd"), "Saturday");
477 assert_eq!(day(2024, 2, 29).write("dddd"), "Thursday");
478 assert_eq!(day(2026, 11, 5).write("dddd"), "Thursday");
479 }
480
481 #[test]
482 fn finds_the_day_of_the_week_at_the_ends_of_32_bits_and_before_the_year_1() {
483 let day = |year, month, day| DateTime {
484 year,
485 month,
486 day,
487 hour: 0,
488 minute: 0,
489 second: 0,
490 };
491 assert_eq!(day(i32::MAX, 1, 1).write("dddd"), "Tuesday");
494 assert_eq!(day(i32::MIN, 1, 1).write("dddd"), "Tuesday");
495 assert_eq!(day(i32::MAX, 12, 31).write("dddd"), "Tuesday");
496 assert_eq!(day(-1, 1, 1).write("dddd"), "Friday");
497 assert_eq!(day(-1, 3, 1).write("dddd"), "Monday");
498 }
499}