1#![forbid(unsafe_code)]
2
3use super::data::{DateSymbols, DateTimeOrder, LocaleData, lookup_locale_data};
6use super::error::{DateTimeError, FormattingError};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10pub enum DateFormatStyle {
11 #[default]
13 Short,
14 Medium,
16 Long,
18 Full,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum TimeFormatStyle {
25 #[default]
27 Short,
28 Medium,
30 Long,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
36pub struct Date {
37 year: i32,
38 month: u8,
39 day: u8,
40}
41
42impl Date {
43 pub fn from_ymd(year: i32, month: u8, day: u8) -> Result<Self, DateTimeError> {
49 if !(1..=12).contains(&month) {
50 return Err(DateTimeError::InvalidMonth(month));
51 }
52
53 let max_days = days_in_month(year, month);
54 if day == 0 || day > max_days {
55 return Err(DateTimeError::InvalidDay {
56 year,
57 month,
58 day,
59 max_days,
60 });
61 }
62
63 Ok(Self { year, month, day })
64 }
65
66 #[inline]
68 #[must_use]
69 pub const fn year(&self) -> i32 {
70 self.year
71 }
72
73 #[inline]
75 #[must_use]
76 pub const fn month(&self) -> u8 {
77 self.month
78 }
79
80 #[inline]
82 #[must_use]
83 pub const fn day(&self) -> u8 {
84 self.day
85 }
86
87 #[must_use]
89 pub fn day_of_week(&self) -> u8 {
90 compute_day_of_week(self.year, self.month, self.day)
91 }
92
93 #[inline]
95 #[must_use]
96 pub const fn is_leap_year(&self) -> bool {
97 is_leap_year(self.year)
98 }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
103pub struct Time {
104 hour: u8,
105 minute: u8,
106 second: u8,
107 millisecond: u16,
108}
109
110impl Time {
111 pub fn from_hms(hour: u8, minute: u8, second: u8) -> Result<Self, DateTimeError> {
116 Self::from_hms_milli(hour, minute, second, 0)
117 }
118
119 pub fn from_hms_milli(
124 hour: u8,
125 minute: u8,
126 second: u8,
127 millisecond: u16,
128 ) -> Result<Self, DateTimeError> {
129 if hour > 23 {
130 return Err(DateTimeError::InvalidHour(hour));
131 }
132 if minute > 59 {
133 return Err(DateTimeError::InvalidMinute(minute));
134 }
135 if second > 59 {
136 return Err(DateTimeError::InvalidSecond(second));
137 }
138 if millisecond > 999 {
139 return Err(DateTimeError::InvalidMillisecond(millisecond));
140 }
141
142 Ok(Self {
143 hour,
144 minute,
145 second,
146 millisecond,
147 })
148 }
149
150 #[inline]
152 #[must_use]
153 pub const fn hour(&self) -> u8 {
154 self.hour
155 }
156
157 #[inline]
159 #[must_use]
160 pub const fn minute(&self) -> u8 {
161 self.minute
162 }
163
164 #[inline]
166 #[must_use]
167 pub const fn second(&self) -> u8 {
168 self.second
169 }
170
171 #[inline]
173 #[must_use]
174 pub const fn millisecond(&self) -> u16 {
175 self.millisecond
176 }
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
181pub struct DateTime {
182 date: Date,
183 time: Time,
184 timezone_offset_minutes: Option<i16>,
186}
187
188impl DateTime {
189 #[must_use]
191 pub const fn new(date: Date, time: Time) -> Self {
192 Self {
193 date,
194 time,
195 timezone_offset_minutes: None,
196 }
197 }
198
199 pub fn with_timezone_offset(
204 date: Date,
205 time: Time,
206 offset_minutes: i16,
207 ) -> Result<Self, DateTimeError> {
208 if !(-720..=840).contains(&offset_minutes) {
209 return Err(DateTimeError::InvalidTimezoneOffset(offset_minutes));
210 }
211 Ok(Self {
212 date,
213 time,
214 timezone_offset_minutes: Some(offset_minutes),
215 })
216 }
217
218 pub fn from_ymd_hms(
220 year: i32,
221 month: u8,
222 day: u8,
223 hour: u8,
224 minute: u8,
225 second: u8,
226 ) -> Result<Self, DateTimeError> {
227 let date = Date::from_ymd(year, month, day)?;
228 let time = Time::from_hms(hour, minute, second)?;
229 Ok(Self::new(date, time))
230 }
231
232 #[inline]
234 #[must_use]
235 pub const fn date(&self) -> &Date {
236 &self.date
237 }
238
239 #[inline]
241 #[must_use]
242 pub const fn time(&self) -> &Time {
243 &self.time
244 }
245
246 #[inline]
248 #[must_use]
249 pub const fn timezone_offset_minutes(&self) -> Option<i16> {
250 self.timezone_offset_minutes
251 }
252}
253
254#[derive(Debug, Clone)]
256pub struct DateTimeFormatter {
257 locale_tag: String,
258 symbols: DateSymbols,
259}
260
261impl DateTimeFormatter {
262 pub fn for_locale(locale: &str) -> Result<Self, FormattingError> {
267 let data = lookup_locale_data(locale)
268 .ok_or_else(|| FormattingError::UnsupportedLocale(locale.to_string()))?;
269 Ok(Self::from_data(data))
270 }
271
272 #[must_use]
274 pub fn from_data(data: &'static LocaleData) -> Self {
275 Self {
276 locale_tag: data.tag.to_string(),
277 symbols: data.date,
278 }
279 }
280
281 #[must_use]
283 pub fn locale(&self) -> &str {
284 &self.locale_tag
285 }
286
287 #[must_use]
289 pub fn format_date(&self, date: &Date, style: DateFormatStyle) -> String {
290 let month_idx = (date.month() - 1) as usize;
291 let month_abbr = self.symbols.months_abbr[month_idx];
292 let month_full = self.symbols.months_full[month_idx];
293 let dow_idx = date.day_of_week() as usize;
294 let day_full = self.symbols.days_full[dow_idx];
295
296 let base_tag = self.locale_tag.split(['-', '_']).next().unwrap_or("en");
297
298 match base_tag {
299 "en" => match style {
300 DateFormatStyle::Short => {
301 format!("{:02}/{:02}/{:04}", date.month(), date.day(), date.year())
302 }
303 DateFormatStyle::Medium => {
304 format!("{} {}, {}", month_abbr, date.day(), date.year())
305 }
306 DateFormatStyle::Long => {
307 format!("{} {}, {}", month_full, date.day(), date.year())
308 }
309 DateFormatStyle::Full => {
310 format!(
311 "{}, {} {}, {}",
312 day_full,
313 month_full,
314 date.day(),
315 date.year()
316 )
317 }
318 },
319 "de" => match style {
320 DateFormatStyle::Short => {
321 format!("{:02}.{:02}.{:04}", date.day(), date.month(), date.year())
322 }
323 DateFormatStyle::Medium => {
324 format!("{}. {} {}", date.day(), month_abbr, date.year())
325 }
326 DateFormatStyle::Long => {
327 format!("{}. {} {}", date.day(), month_full, date.year())
328 }
329 DateFormatStyle::Full => {
330 format!(
331 "{}, {}. {} {}",
332 day_full,
333 date.day(),
334 month_full,
335 date.year()
336 )
337 }
338 },
339 "fr" => match style {
340 DateFormatStyle::Short => {
341 format!("{:02}/{:02}/{:04}", date.day(), date.month(), date.year())
342 }
343 DateFormatStyle::Medium => {
344 format!("{} {} {}", date.day(), month_abbr, date.year())
345 }
346 DateFormatStyle::Long => {
347 format!("{} {} {}", date.day(), month_full, date.year())
348 }
349 DateFormatStyle::Full => {
350 format!("{} {} {} {}", day_full, date.day(), month_full, date.year())
351 }
352 },
353 "es" => match style {
354 DateFormatStyle::Short => {
355 format!("{:02}/{:02}/{:04}", date.day(), date.month(), date.year())
356 }
357 DateFormatStyle::Medium => {
358 format!("{} {} {}", date.day(), month_abbr, date.year())
359 }
360 DateFormatStyle::Long => {
361 format!("{} de {} de {}", date.day(), month_full, date.year())
362 }
363 DateFormatStyle::Full => {
364 format!(
365 "{}, {} de {} de {}",
366 day_full,
367 date.day(),
368 month_full,
369 date.year()
370 )
371 }
372 },
373 "ru" => match style {
374 DateFormatStyle::Short => {
375 format!("{:02}.{:02}.{:04}", date.day(), date.month(), date.year())
376 }
377 DateFormatStyle::Medium => {
378 format!("{} {} {} г.", date.day(), month_abbr, date.year())
379 }
380 DateFormatStyle::Long => {
381 format!("{} {} {} г.", date.day(), month_full, date.year())
382 }
383 DateFormatStyle::Full => {
384 format!(
385 "{}, {} {} {} г.",
386 day_full,
387 date.day(),
388 month_full,
389 date.year()
390 )
391 }
392 },
393 "ar" => match style {
394 DateFormatStyle::Short => {
395 format!("{:02}/{:02}/{:04}", date.day(), date.month(), date.year())
396 }
397 DateFormatStyle::Medium => {
398 format!("{} {}، {}", date.day(), month_abbr, date.year())
399 }
400 DateFormatStyle::Long => {
401 format!("{} {} {}", date.day(), month_full, date.year())
402 }
403 DateFormatStyle::Full => {
404 format!(
405 "{}، {} {} {}",
406 day_full,
407 date.day(),
408 month_full,
409 date.year()
410 )
411 }
412 },
413 "ja" => match style {
414 DateFormatStyle::Short | DateFormatStyle::Medium => {
415 format!("{:04}/{:02}/{:02}", date.year(), date.month(), date.day())
416 }
417 DateFormatStyle::Long => {
418 format!("{}年{}月{}日", date.year(), date.month(), date.day())
419 }
420 DateFormatStyle::Full => {
421 format!(
422 "{}年{}月{}日 {}",
423 date.year(),
424 date.month(),
425 date.day(),
426 day_full
427 )
428 }
429 },
430 _ => {
431 format!("{:04}-{:02}-{:02}", date.year(), date.month(), date.day())
433 }
434 }
435 }
436
437 #[must_use]
439 pub fn format_time(&self, time: &Time, style: TimeFormatStyle) -> String {
440 let (hour_str, am_pm_str) = if self.symbols.is_24h {
441 (format!("{:02}", time.hour()), None)
442 } else {
443 let (h12, am_pm) = if time.hour() == 0 {
444 (12, self.symbols.am_pm.0)
445 } else if time.hour() < 12 {
446 (time.hour(), self.symbols.am_pm.0)
447 } else if time.hour() == 12 {
448 (12, self.symbols.am_pm.1)
449 } else {
450 (time.hour() - 12, self.symbols.am_pm.1)
451 };
452 (h12.to_string(), Some(am_pm))
453 };
454
455 match style {
456 TimeFormatStyle::Short => {
457 if let Some(ap) = am_pm_str {
458 format!("{}:{:02} {}", hour_str, time.minute(), ap)
459 } else {
460 format!("{}:{:02}", hour_str, time.minute())
461 }
462 }
463 TimeFormatStyle::Medium | TimeFormatStyle::Long => {
464 if let Some(ap) = am_pm_str {
465 format!(
466 "{}:{:02}:{:02} {}",
467 hour_str,
468 time.minute(),
469 time.second(),
470 ap
471 )
472 } else {
473 format!("{}:{:02}:{:02}", hour_str, time.minute(), time.second())
474 }
475 }
476 }
477 }
478
479 #[must_use]
481 pub fn format_datetime(
482 &self,
483 dt: &DateTime,
484 date_style: DateFormatStyle,
485 time_style: TimeFormatStyle,
486 ) -> String {
487 let date_str = self.format_date(dt.date(), date_style);
488 let mut time_str = self.format_time(dt.time(), time_style);
489
490 if time_style == TimeFormatStyle::Long
491 && let Some(offset) = dt.timezone_offset_minutes()
492 {
493 time_str.push(' ');
494 time_str.push_str(&format_tz_offset(offset));
495 }
496
497 let separator = self.symbols.datetime_separator;
498 match self.symbols.datetime_order {
499 DateTimeOrder::DateThenTime => format!("{date_str}{separator}{time_str}"),
500 DateTimeOrder::TimeThenDate => format!("{time_str}{separator}{date_str}"),
501 }
502 }
503}
504
505fn format_tz_offset(offset_minutes: i16) -> String {
507 if offset_minutes == 0 {
508 return "UTC".to_string();
509 }
510 let sign = if offset_minutes >= 0 { '+' } else { '-' };
511 let abs_mins = offset_minutes.unsigned_abs();
512 let hours = abs_mins / 60;
513 let mins = abs_mins % 60;
514 format!("UTC{}{:02}:{:02}", sign, hours, mins)
515}
516
517#[inline]
519pub const fn is_leap_year(year: i32) -> bool {
520 (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
521}
522
523pub const fn days_in_month(year: i32, month: u8) -> u8 {
525 match month {
526 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
527 4 | 6 | 9 | 11 => 30,
528 2 => {
529 if is_leap_year(year) {
530 29
531 } else {
532 28
533 }
534 }
535 _ => 0,
536 }
537}
538
539fn compute_day_of_week(y: i32, m: u8, d: u8) -> u8 {
556 const T: [i64; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
557 let y = i64::from(y);
558 let y_adj = if m < 3 { y - 1 } else { y };
559 let dow = (y_adj + y_adj.div_euclid(4) - y_adj.div_euclid(100)
560 + y_adj.div_euclid(400)
561 + T[(m - 1) as usize]
562 + i64::from(d))
563 .rem_euclid(7);
564 let dow_iso = (dow + 6) % 7;
567 dow_iso as u8
568}
569
570#[cfg(test)]
571mod tests {
572 use super::*;
573
574 #[test]
575 fn test_leap_years() {
576 assert!(is_leap_year(2024));
577 assert!(!is_leap_year(2023));
578 assert!(is_leap_year(2000));
579 assert!(!is_leap_year(1900));
580 assert!(is_leap_year(2028));
581 }
582
583 #[test]
584 fn test_days_in_month() {
585 assert_eq!(days_in_month(2024, 2), 29);
586 assert_eq!(days_in_month(2023, 2), 28);
587 assert_eq!(days_in_month(2026, 1), 31);
588 assert_eq!(days_in_month(2026, 4), 30);
589 }
590
591 #[test]
592 fn test_date_validation() {
593 assert!(Date::from_ymd(2024, 2, 29).is_ok());
594 assert!(Date::from_ymd(2023, 2, 29).is_err());
595 assert!(Date::from_ymd(2026, 13, 1).is_err());
596 assert!(Date::from_ymd(2026, 0, 1).is_err());
597 assert!(Date::from_ymd(2026, 1, 32).is_err());
598 }
599
600 #[test]
601 fn test_time_validation() {
602 assert!(Time::from_hms(23, 59, 59).is_ok());
603 assert!(Time::from_hms(24, 0, 0).is_err());
604 assert!(Time::from_hms(12, 60, 0).is_err());
605 assert!(Time::from_hms(12, 0, 60).is_err());
606 }
607
608 #[test]
609 fn test_day_of_week() {
610 let date = Date::from_ymd(2026, 9, 19).unwrap();
612 assert_eq!(date.day_of_week(), 5);
613
614 let sun = Date::from_ymd(2026, 9, 20).unwrap();
616 assert_eq!(sun.day_of_week(), 6);
617
618 let mon = Date::from_ymd(2026, 9, 21).unwrap();
620 assert_eq!(mon.day_of_week(), 0);
621 }
622
623 #[test]
624 fn day_of_week_spans_every_year_from_ymd_accepts() {
625 for date in [
630 Date::from_ymd(i32::MAX, 3, 1).unwrap(),
631 Date::from_ymd(i32::MAX, 1, 1).unwrap(),
632 Date::from_ymd(i32::MIN, 1, 1).unwrap(),
633 Date::from_ymd(i32::MIN, 12, 31).unwrap(),
634 ] {
635 assert!(date.day_of_week() <= 6, "{date:?}");
638 let fmt = DateTimeFormatter::for_locale("en").unwrap();
639 assert!(!fmt.format_date(&date, DateFormatStyle::Full).is_empty());
640 }
641 }
642
643 #[test]
644 fn day_of_week_uses_floor_division_below_year_one() {
645 assert_eq!(Date::from_ymd(2000, 3, 1).unwrap().day_of_week(), 2); assert_eq!(Date::from_ymd(0, 3, 1).unwrap().day_of_week(), 2); assert_eq!(Date::from_ymd(0, 1, 1).unwrap().day_of_week(), 5); assert_eq!(Date::from_ymd(1, 1, 1).unwrap().day_of_week(), 0); assert_eq!(Date::from_ymd(-1, 1, 1).unwrap().day_of_week(), 4); }
668
669 #[test]
670 fn test_date_formatting_styles() {
671 let date = Date::from_ymd(2026, 9, 19).unwrap();
672
673 let fmt_en = DateTimeFormatter::for_locale("en").unwrap();
674 assert_eq!(
675 fmt_en.format_date(&date, DateFormatStyle::Short),
676 "09/19/2026"
677 );
678 assert_eq!(
679 fmt_en.format_date(&date, DateFormatStyle::Medium),
680 "Sep 19, 2026"
681 );
682 assert_eq!(
683 fmt_en.format_date(&date, DateFormatStyle::Long),
684 "September 19, 2026"
685 );
686 assert_eq!(
687 fmt_en.format_date(&date, DateFormatStyle::Full),
688 "Saturday, September 19, 2026"
689 );
690
691 let fmt_de = DateTimeFormatter::for_locale("de").unwrap();
692 assert_eq!(
693 fmt_de.format_date(&date, DateFormatStyle::Short),
694 "19.09.2026"
695 );
696 assert_eq!(
697 fmt_de.format_date(&date, DateFormatStyle::Medium),
698 "19. Sept. 2026"
699 );
700 assert_eq!(
701 fmt_de.format_date(&date, DateFormatStyle::Long),
702 "19. September 2026"
703 );
704 assert_eq!(
705 fmt_de.format_date(&date, DateFormatStyle::Full),
706 "Samstag, 19. September 2026"
707 );
708
709 let fmt_ja = DateTimeFormatter::for_locale("ja").unwrap();
710 assert_eq!(
711 fmt_ja.format_date(&date, DateFormatStyle::Short),
712 "2026/09/19"
713 );
714 assert_eq!(
715 fmt_ja.format_date(&date, DateFormatStyle::Long),
716 "2026年9月19日"
717 );
718 assert_eq!(
719 fmt_ja.format_date(&date, DateFormatStyle::Full),
720 "2026年9月19日 土曜日"
721 );
722 }
723
724 #[test]
725 fn test_time_formatting_styles() {
726 let t_afternoon = Time::from_hms(14, 30, 45).unwrap();
727 let t_morning = Time::from_hms(9, 5, 0).unwrap();
728
729 let fmt_en = DateTimeFormatter::for_locale("en").unwrap();
731 assert_eq!(
732 fmt_en.format_time(&t_afternoon, TimeFormatStyle::Short),
733 "2:30 PM"
734 );
735 assert_eq!(
736 fmt_en.format_time(&t_afternoon, TimeFormatStyle::Medium),
737 "2:30:45 PM"
738 );
739 assert_eq!(
740 fmt_en.format_time(&t_morning, TimeFormatStyle::Short),
741 "9:05 AM"
742 );
743
744 let fmt_de = DateTimeFormatter::for_locale("de").unwrap();
746 assert_eq!(
747 fmt_de.format_time(&t_afternoon, TimeFormatStyle::Short),
748 "14:30"
749 );
750 assert_eq!(
751 fmt_de.format_time(&t_afternoon, TimeFormatStyle::Medium),
752 "14:30:45"
753 );
754 assert_eq!(
755 fmt_de.format_time(&t_morning, TimeFormatStyle::Short),
756 "09:05"
757 );
758 }
759
760 #[test]
761 fn test_combined_datetime() {
762 let dt = DateTime::from_ymd_hms(2026, 9, 19, 14, 30, 0).unwrap();
763
764 let fmt_en = DateTimeFormatter::for_locale("en").unwrap();
765 assert_eq!(
766 fmt_en.format_datetime(&dt, DateFormatStyle::Short, TimeFormatStyle::Short),
767 "09/19/2026, 2:30 PM"
768 );
769
770 let fmt_de = DateTimeFormatter::for_locale("de").unwrap();
771 assert_eq!(
772 fmt_de.format_datetime(&dt, DateFormatStyle::Short, TimeFormatStyle::Short),
773 "19.09.2026, 14:30"
774 );
775 }
776
777 #[test]
778 fn combined_datetime_follows_the_locale_order() {
779 let en = lookup_locale_data("en").unwrap();
782 let time_first: &'static LocaleData = Box::leak(Box::new(LocaleData {
783 date: DateSymbols {
784 datetime_order: DateTimeOrder::TimeThenDate,
785 ..en.date
786 },
787 ..*en
788 }));
789 let dt = DateTime::from_ymd_hms(2026, 9, 19, 14, 30, 0).unwrap();
790 assert_eq!(
791 DateTimeFormatter::from_data(time_first).format_datetime(
792 &dt,
793 DateFormatStyle::Short,
794 TimeFormatStyle::Short
795 ),
796 "2:30 PM, 09/19/2026"
797 );
798 }
799
800 #[test]
801 fn test_timezone_formatting() {
802 let date = Date::from_ymd(2026, 9, 19).unwrap();
803 let time = Time::from_hms(14, 30, 0).unwrap();
804 let dt_tz = DateTime::with_timezone_offset(date, time, 120).unwrap();
805
806 let fmt = DateTimeFormatter::for_locale("en").unwrap();
807 let formatted = fmt.format_datetime(&dt_tz, DateFormatStyle::Short, TimeFormatStyle::Long);
808 assert_eq!(formatted, "09/19/2026, 2:30:00 PM UTC+02:00");
809 }
810}