1use core::fmt::{self, Write};
2
3use crate::date_time::{DateTimeLocale, ENGLISH};
4
5#[cfg(feature = "alloc")]
6use alloc::string::String;
7
8fn decompose_unix_timestamp(unix_timestamp: i64) -> (u16, u8, u8, u8, u8, u8) {
9 const SECONDS_IN_MINUTE: i64 = 60;
10 const SECONDS_IN_HOUR: i64 = 60 * SECONDS_IN_MINUTE;
11 const SECONDS_IN_DAY: i64 = 24 * SECONDS_IN_HOUR;
12 const DAYS_IN_YEAR: i64 = 365;
13 const DAYS_IN_LEAP_YEAR: i64 = 366;
14
15 let mut year: i64 = 1970;
16 let mut days_since_epoch = unix_timestamp.div_euclid(SECONDS_IN_DAY);
17 let mut remaining_seconds = unix_timestamp.rem_euclid(SECONDS_IN_DAY);
18
19 while days_since_epoch
20 >= if is_leap_year(year) {
21 DAYS_IN_LEAP_YEAR
22 } else {
23 DAYS_IN_YEAR
24 }
25 {
26 days_since_epoch -= if is_leap_year(year) {
27 DAYS_IN_LEAP_YEAR
28 } else {
29 DAYS_IN_YEAR
30 };
31 year += 1;
32 }
33
34 while days_since_epoch < 0 {
35 year -= 1;
36 days_since_epoch += if is_leap_year(year) {
37 DAYS_IN_LEAP_YEAR
38 } else {
39 DAYS_IN_YEAR
40 };
41 }
42
43 let mut month = 0;
44 while days_since_epoch >= days_in_month(year, month) {
45 days_since_epoch -= days_in_month(year, month);
46 month += 1;
47 }
48
49 let day = days_since_epoch + 1;
50
51 let hour = remaining_seconds / SECONDS_IN_HOUR;
52 remaining_seconds %= SECONDS_IN_HOUR;
53 let minute = remaining_seconds / SECONDS_IN_MINUTE;
54 let second = remaining_seconds % SECONDS_IN_MINUTE;
55
56 (
57 year as u16,
58 month as u8 + 1,
59 day as u8,
60 hour as u8,
61 minute as u8,
62 second as u8,
63 )
64}
65
66fn is_leap_year(year: i64) -> bool {
67 (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
68}
69
70fn days_in_month(year: i64, month: usize) -> i64 {
71 const DAYS_IN_MONTH: [i64; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
72
73 if month == 1 && is_leap_year(year) {
74 29
75 } else {
76 DAYS_IN_MONTH[month]
77 }
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub struct DateTimeFormatter {
108 locale: DateTimeLocale,
109 offset: i32,
110}
111
112impl DateTimeFormatter {
113 pub const fn new(locale: DateTimeLocale) -> Self {
115 DateTimeFormatter { locale, offset: 0 }
116 }
117
118 pub const fn with_locale(self, locale: DateTimeLocale) -> Self {
120 DateTimeFormatter { locale, ..self }
121 }
122
123 pub const fn with_utc_offset(self, seconds: i32) -> Self {
125 DateTimeFormatter {
126 offset: seconds,
127 ..self
128 }
129 }
130
131 pub const fn locale(&self) -> &DateTimeLocale {
133 &self.locale
134 }
135
136 pub const fn utc_offset(&self) -> i32 {
138 self.offset
139 }
140
141 pub fn write<W: Write>(
143 &self,
144 writer: &mut W,
145 unix_timestamp: i64,
146 pattern: &str,
147 ) -> fmt::Result {
148 let local = unix_timestamp.saturating_add(i64::from(self.offset));
149 let (year, month, day, hour, minute, second) = decompose_unix_timestamp(local);
150 let fields = Fields {
151 year,
152 month,
153 day,
154 hour,
155 minute,
156 second,
157 weekday: weekday(local),
158 };
159 self.write_pattern(writer, &fields, pattern, true)
160 }
161
162 pub const fn display<'a>(
173 &'a self,
174 unix_timestamp: i64,
175 pattern: &'a str,
176 ) -> DateTimeDisplay<'a> {
177 DateTimeDisplay {
178 formatter: self,
179 unix_timestamp,
180 pattern,
181 }
182 }
183
184 #[cfg(feature = "alloc")]
187 pub fn format(&self, unix_timestamp: i64, pattern: &str) -> String {
188 let mut output = String::with_capacity(pattern.len() + 16);
189 let _ = self.write(&mut output, unix_timestamp, pattern);
190 output
191 }
192
193 fn write_pattern<W: Write>(
194 &self,
195 writer: &mut W,
196 fields: &Fields,
197 pattern: &str,
198 expand: bool,
199 ) -> fmt::Result {
200 let locale = &self.locale;
201 let mut characters = pattern.chars();
202
203 while let Some(character) = characters.next() {
204 if character != '%' {
205 writer.write_char(character)?;
206 continue;
207 }
208
209 match characters.next() {
210 Some('Y') => write!(writer, "{:04}", fields.year)?,
211 Some('y') => write!(writer, "{:02}", fields.year % 100)?,
212 Some('m') => write!(writer, "{:02}", fields.month)?,
213 Some('d') => write!(writer, "{:02}", fields.day)?,
214 Some('e') => write!(writer, "{:2}", fields.day)?,
215 Some('H') => write!(writer, "{:02}", fields.hour)?,
216 Some('I') => write!(writer, "{:02}", hour_12(fields.hour))?,
217 Some('M') => write!(writer, "{:02}", fields.minute)?,
218 Some('S') => write!(writer, "{:02}", fields.second)?,
219 Some('p') => writer.write_str(if fields.hour < 12 {
220 locale.am
221 } else {
222 locale.pm
223 })?,
224 Some('B') => writer.write_str(locale.months[usize::from(fields.month - 1)])?,
225 Some('b' | 'h') => {
226 writer.write_str(locale.months_abbreviated[usize::from(fields.month - 1)])?
227 }
228 Some('A') => writer.write_str(locale.weekdays[usize::from(fields.weekday)])?,
229 Some('a') => {
230 writer.write_str(locale.weekdays_abbreviated[usize::from(fields.weekday)])?
231 }
232 Some('u') => write!(
233 writer,
234 "{}",
235 if fields.weekday == 0 {
236 7
237 } else {
238 fields.weekday
239 }
240 )?,
241 Some('w') => write!(writer, "{}", fields.weekday)?,
242 Some('z') => {
243 let sign = if self.offset < 0 { '-' } else { '+' };
244 let minutes = self.offset.unsigned_abs() / 60;
245 write!(writer, "{}{:02}{:02}", sign, minutes / 60, minutes % 60)?
246 }
247 Some('O') => match characters.clone().next() {
248 Some('B') => {
249 characters.next();
250 writer.write_str(locale.months_standalone[usize::from(fields.month - 1)])?
251 }
252 _ => writer.write_str("%O")?,
253 },
254 Some('x') if expand => self.write_pattern(writer, fields, locale.date, false)?,
255 Some('X') if expand => self.write_pattern(writer, fields, locale.time, false)?,
256 Some('c') if expand => {
257 self.write_pattern(writer, fields, locale.date, false)?;
258 writer.write_char(' ')?;
259 self.write_pattern(writer, fields, locale.time, false)?
260 }
261 Some('%') => writer.write_char('%')?,
262 Some(other) => {
263 writer.write_char('%')?;
264 writer.write_char(other)?;
265 }
266 None => writer.write_char('%')?,
267 }
268 }
269
270 Ok(())
271 }
272}
273
274struct Fields {
275 year: u16,
276 month: u8,
277 day: u8,
278 hour: u8,
279 minute: u8,
280 second: u8,
281 weekday: u8,
282}
283
284fn weekday(unix_timestamp: i64) -> u8 {
285 (unix_timestamp.div_euclid(86_400) + 4).rem_euclid(7) as u8
286}
287
288pub struct DateTimeDisplay<'a> {
290 formatter: &'a DateTimeFormatter,
291 unix_timestamp: i64,
292 pattern: &'a str,
293}
294
295impl fmt::Display for DateTimeDisplay<'_> {
296 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297 self.formatter.write(f, self.unix_timestamp, self.pattern)
298 }
299}
300
301pub fn write_unix_timestamp<W: Write>(
311 writer: &mut W,
312 unix_timestamp: i64,
313 pattern: &str,
314) -> fmt::Result {
315 DateTimeFormatter::new(ENGLISH).write(writer, unix_timestamp, pattern)
316}
317
318#[cfg(feature = "alloc")]
321pub fn format_unix_timestamp(unix_timestamp: i64, pattern: &str) -> String {
322 DateTimeFormatter::new(ENGLISH).format(unix_timestamp, pattern)
323}
324
325const fn hour_12(hour_24: u8) -> u8 {
326 match hour_24 % 12 {
327 0 => 12,
328 value => value,
329 }
330}
331
332#[cfg(all(test, feature = "alloc"))]
333mod tests {
334 use super::*;
335
336 #[test]
337 fn format_24_hour_time() {
338 let timestamp = 13 * 3600 + 5 * 60;
339 assert_eq!(format_unix_timestamp(timestamp, "%H:%M"), "13:05");
340 }
341
342 #[test]
343 fn format_12_hour_time_with_am_pm() {
344 let midnight = 0;
345 let afternoon = 13 * 3600 + 5 * 60;
346
347 assert_eq!(format_unix_timestamp(midnight, "%I:%M %p"), "12:00 AM");
348 assert_eq!(format_unix_timestamp(afternoon, "%I:%M %p"), "01:05 PM");
349 }
350
351 #[test]
352 fn format_date_and_time() {
353 assert_eq!(
354 format_unix_timestamp(0, "%Y-%m-%d %H:%M:%S"),
355 "1970-01-01 00:00:00"
356 );
357 }
358
359 #[test]
360 fn format_negative_unix_time() {
361 assert_eq!(
362 format_unix_timestamp(-1, "%Y-%m-%d %H:%M:%S"),
363 "1969-12-31 23:59:59"
364 );
365 }
366
367 #[test]
368 fn unix_epoch_is_correct() {
369 assert_eq!(decompose_unix_timestamp(0), (1970, 1, 1, 0, 0, 0));
370 }
371
372 #[test]
373 fn one_second_before_epoch_is_correct() {
374 assert_eq!(decompose_unix_timestamp(-1), (1969, 12, 31, 23, 59, 59));
375 }
376
377 #[test]
378 fn one_day_before_epoch_is_correct() {
379 assert_eq!(decompose_unix_timestamp(-86_400), (1969, 12, 31, 0, 0, 0));
380 }
381
382 #[test]
383 fn leap_day_2024_is_correct() {
384 assert_eq!(
385 decompose_unix_timestamp(1_709_164_800),
386 (2024, 2, 29, 0, 0, 0)
387 );
388 }
389
390 #[test]
391 fn leap_year_rules_are_correct() {
392 assert!(is_leap_year(2000));
393 assert!(!is_leap_year(1900));
394 assert!(is_leap_year(2024));
395 assert!(!is_leap_year(2023));
396 }
397
398 #[test]
399 fn february_days_are_correct() {
400 assert_eq!(days_in_month(2024, 1), 29);
401 assert_eq!(days_in_month(2023, 1), 28);
402 }
403
404 #[test]
405 fn only_time() {
406 assert_eq!(format_unix_timestamp(3661, "%H:%M:%S"), "01:01:01");
407 }
408
409 #[test]
410 fn only_date() {
411 assert_eq!(format_unix_timestamp(0, "%Y-%m-%d"), "1970-01-01");
412 }
413
414 #[test]
415 fn literal_percent() {
416 assert_eq!(format_unix_timestamp(0, "100%%"), "100%");
417 }
418
419 #[test]
420 fn unknown_format_token() {
421 assert_eq!(format_unix_timestamp(0, "%q"), "%q");
422 }
423
424 #[test]
425 fn partial_percent_at_end() {
426 assert_eq!(format_unix_timestamp(0, "end%"), "end%");
427 }
428
429 #[test]
430 fn mixed_literal_and_format() {
431 assert_eq!(
432 format_unix_timestamp(0, "Date: %Y-%m-%d, Time: %H:%M:%S"),
433 "Date: 1970-01-01, Time: 00:00:00"
434 );
435 }
436
437 #[test]
438 fn noon_is_12_pm() {
439 let noon = 12 * 3600;
440 assert_eq!(decompose_unix_timestamp(noon), (1970, 1, 1, 12, 0, 0));
441 }
442
443 #[test]
444 fn hour_12_midnight() {
445 assert_eq!(hour_12(0), 12);
446 }
447
448 #[test]
449 fn hour_12_noon() {
450 assert_eq!(hour_12(12), 12);
451 }
452
453 #[test]
454 fn hour_12_various() {
455 assert_eq!(hour_12(1), 1);
456 assert_eq!(hour_12(11), 11);
457 assert_eq!(hour_12(13), 1);
458 assert_eq!(hour_12(23), 11);
459 }
460
461 #[test]
462 fn format_12_hour_noon() {
463 let noon = 12 * 3600;
464 assert_eq!(format_unix_timestamp(noon, "%I:%M %p"), "12:00 PM");
465 }
466
467 #[test]
468 fn format_12_hour_midnight() {
469 assert_eq!(format_unix_timestamp(0, "%I:%M %p"), "12:00 AM");
470 }
471
472 #[test]
473 fn year_2000_timestamp() {
474 let ts = 946684800; assert_eq!(format_unix_timestamp(ts, "%Y"), "2000");
476 }
477
478 #[test]
479 fn leap_year_2000() {
480 let ts = 951782400; assert_eq!(decompose_unix_timestamp(ts), (2000, 2, 29, 0, 0, 0));
482 assert_eq!(format_unix_timestamp(ts, "%Y-%m-%d"), "2000-02-29");
483 }
484
485 #[test]
486 fn non_leap_year_1900() {
487 assert!(!is_leap_year(1900));
488 }
489
490 #[test]
491 fn century_boundary_2000_is_leap() {
492 assert!(is_leap_year(2000));
493 }
494
495 #[test]
496 fn year_2038_problem() {
497 let ts = 2147483648i64; assert_eq!(format_unix_timestamp(ts, "%Y"), "2038");
499 }
500
501 #[test]
502 fn empty_pattern() {
503 assert_eq!(format_unix_timestamp(0, ""), "");
504 }
505
506 #[test]
507 fn no_format_tokens() {
508 assert_eq!(
509 format_unix_timestamp(0, "just literal text"),
510 "just literal text"
511 );
512 }
513
514 #[test]
515 fn negative_timestamp_bce_date() {
516 let ts = -31536000i64; assert_eq!(format_unix_timestamp(ts, "%Y-%m-%d"), "1969-01-01");
518 }
519
520 #[test]
521 fn multiple_percent_escape() {
522 assert_eq!(format_unix_timestamp(0, "%%Y%%m%%d%%"), "%Y%m%d%");
523 }
524}
525
526#[cfg(test)]
527mod writer_tests {
528 use super::*;
529
530 struct Buffer {
531 bytes: [u8; 64],
532 length: usize,
533 }
534
535 impl Buffer {
536 fn new() -> Self {
537 Buffer {
538 bytes: [0; 64],
539 length: 0,
540 }
541 }
542
543 fn as_str(&self) -> &str {
544 core::str::from_utf8(&self.bytes[..self.length]).unwrap()
545 }
546 }
547
548 impl Write for Buffer {
549 fn write_str(&mut self, value: &str) -> fmt::Result {
550 let end = self.length + value.len();
551 if end > self.bytes.len() {
552 return Err(fmt::Error);
553 }
554 self.bytes[self.length..end].copy_from_slice(value.as_bytes());
555 self.length = end;
556 Ok(())
557 }
558 }
559
560 #[test]
561 fn write_epoch() {
562 let mut buffer = Buffer::new();
563 write_unix_timestamp(&mut buffer, 0, "%Y-%m-%d %H:%M:%S").unwrap();
564 assert_eq!(buffer.as_str(), "1970-01-01 00:00:00");
565 }
566
567 #[test]
568 fn write_12_hour_time() {
569 let mut buffer = Buffer::new();
570 write_unix_timestamp(&mut buffer, 13 * 3600 + 5 * 60, "%I:%M %p %%").unwrap();
571 assert_eq!(buffer.as_str(), "01:05 PM %");
572 }
573
574 #[test]
575 fn write_propagates_errors() {
576 let mut buffer = Buffer::new();
577 let pattern = "%Y-%m-%d %H:%M:%S %Y-%m-%d %H:%M:%S %Y-%m-%d %H:%M:%S %Y-%m-%d";
578 assert!(write_unix_timestamp(&mut buffer, 0, pattern).is_err());
579 }
580}
581
582#[cfg(test)]
583mod localized_tests {
584 use super::*;
585 use crate::date_time::date_time_locale;
586
587 struct Buffer {
588 bytes: [u8; 128],
589 length: usize,
590 }
591
592 impl Write for Buffer {
593 fn write_str(&mut self, value: &str) -> fmt::Result {
594 let end = self.length + value.len();
595 if end > self.bytes.len() {
596 return Err(fmt::Error);
597 }
598 self.bytes[self.length..end].copy_from_slice(value.as_bytes());
599 self.length = end;
600 Ok(())
601 }
602 }
603
604 fn render(formatter: &DateTimeFormatter, unix_timestamp: i64, pattern: &str) -> Buffer {
605 let mut buffer = Buffer {
606 bytes: [0; 128],
607 length: 0,
608 };
609 formatter
610 .write(&mut buffer, unix_timestamp, pattern)
611 .unwrap();
612 buffer
613 }
614
615 fn assert_renders(
616 formatter: &DateTimeFormatter,
617 unix_timestamp: i64,
618 pattern: &str,
619 expected: &str,
620 ) {
621 let buffer = render(formatter, unix_timestamp, pattern);
622 assert_eq!(
623 core::str::from_utf8(&buffer.bytes[..buffer.length]).unwrap(),
624 expected
625 );
626 }
627
628 const OCTOBER_13_2026: i64 = 1_791_884_800;
629
630 #[test]
631 fn english_names_and_patterns() {
632 let formatter = DateTimeFormatter::new(ENGLISH);
633 assert_renders(
634 &formatter,
635 0,
636 "%A %a %B %b %h",
637 "Thursday Thu January Jan Jan",
638 );
639 assert_renders(&formatter, OCTOBER_13_2026, "%c", "10/13/2026 09:46:40 AM");
640 assert_renders(&formatter, OCTOBER_13_2026, "%y %e %u %w", "26 13 2 2");
641 }
642
643 #[test]
644 fn french_names_and_patterns() {
645 let formatter = DateTimeFormatter::new(date_time_locale("fr"));
646 assert_renders(
647 &formatter,
648 OCTOBER_13_2026,
649 "%A %d %B %Y, %X",
650 "mardi 13 octobre 2026, 09:46:40",
651 );
652 assert_renders(&formatter, OCTOBER_13_2026, "%x", "13/10/2026");
653 assert_renders(&formatter, OCTOBER_13_2026, "%a %b", "mar. oct.");
654 }
655
656 #[test]
657 fn standalone_months() {
658 let formatter = DateTimeFormatter::new(date_time_locale("ru"));
659 assert_renders(
660 &formatter,
661 OCTOBER_13_2026,
662 "%d %B / %OB %Y",
663 "13 октября / октябрь 2026",
664 );
665 assert_renders(&formatter, OCTOBER_13_2026, "%Oq", "%Oq");
666 }
667
668 #[test]
669 fn localized_am_pm() {
670 let formatter = DateTimeFormatter::new(date_time_locale("ko"));
671 assert_renders(&formatter, OCTOBER_13_2026, "%X", "오전 09:46:40");
672 assert_renders(&formatter, OCTOBER_13_2026 + 6 * 3600, "%p", "오후");
673 }
674
675 #[test]
676 fn utc_offset_shifts_time_and_prints_z() {
677 let paris = DateTimeFormatter::new(ENGLISH).with_utc_offset(2 * 3600);
678 assert_renders(&paris, OCTOBER_13_2026, "%H:%M %z", "11:46 +0200");
679 let newfoundland = DateTimeFormatter::new(ENGLISH).with_utc_offset(-(3 * 3600 + 1800));
680 assert_renders(
681 &newfoundland,
682 OCTOBER_13_2026,
683 "%d %H:%M %z",
684 "13 06:16 -0330",
685 );
686 let before_midnight = DateTimeFormatter::new(ENGLISH).with_utc_offset(-10 * 3600);
687 assert_renders(&before_midnight, OCTOBER_13_2026, "%A %d", "Monday 12");
688 assert_renders(&DateTimeFormatter::new(ENGLISH), 0, "%z", "+0000");
689 }
690
691 #[test]
692 fn weekday_before_epoch() {
693 assert_renders(&DateTimeFormatter::new(ENGLISH), -1, "%A", "Wednesday");
694 assert_renders(
695 &DateTimeFormatter::new(ENGLISH),
696 -86_400 * 4,
697 "%A",
698 "Sunday",
699 );
700 }
701
702 #[test]
703 fn patterns_do_not_expand_recursively() {
704 let formatter = DateTimeFormatter::new(DateTimeLocale {
705 date: "%x",
706 ..date_time_locale("en")
707 });
708 assert_renders(&formatter, 0, "%x", "%x");
709 }
710
711 #[test]
712 fn display_adapter() {
713 let formatter = DateTimeFormatter::new(ENGLISH);
714 let mut buffer = Buffer {
715 bytes: [0; 128],
716 length: 0,
717 };
718 write!(buffer, "[{}]", formatter.display(0, "%Y-%m-%d")).unwrap();
719 assert_eq!(&buffer.bytes[..buffer.length], b"[1970-01-01]");
720 }
721
722 #[test]
723 fn reports_writer_errors() {
724 let mut buffer = Buffer {
725 bytes: [0; 128],
726 length: 120,
727 };
728 assert!(
729 DateTimeFormatter::new(ENGLISH)
730 .write(&mut buffer, 0, "%A %B")
731 .is_err()
732 );
733 }
734}