1mod find;
4
5#[doc(inline)]
6#[cfg(feature = "alloc")]
7pub use find::FoundDateTimeList;
8#[doc(inline)]
9pub use find::{FoundDateTimeKind, FoundDateTimeListRefMut};
10
11use crate::constants::*;
12use crate::datetime::find::find_date_time;
13use crate::error::TzError;
14use crate::error::datetime::DateTimeError;
15use crate::timezone::{LocalTimeType, TimeZoneRef};
16use crate::utils::{min, try_into_i32, try_into_i64};
17
18use core::cmp::Ordering;
19use core::fmt;
20use core::ops::{Add, AddAssign, Sub, SubAssign};
21use core::time::Duration;
22#[cfg(feature = "std")]
23use std::time::SystemTime;
24
25#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
27pub struct UtcDateTime {
28 year: i32,
30 month: u8,
32 month_day: u8,
34 hour: u8,
36 minute: u8,
38 second: u8,
40 nanoseconds: u32,
42}
43
44impl fmt::Display for UtcDateTime {
45 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46 format_date_time(f, self.year, self.month, self.month_day, self.hour, self.minute, self.second, self.nanoseconds, 0)
47 }
48}
49
50impl UtcDateTime {
51 pub const UNIX_EPOCH: Self = Self { year: 1970, month: 1, month_day: 1, hour: 0, minute: 0, second: 0, nanoseconds: 0 };
53
54 pub const MIN: Self = Self { year: i32::MIN, month: 1, month_day: 1, hour: 0, minute: 0, second: 0, nanoseconds: 0 };
56
57 pub const MAX: Self = Self { year: i32::MAX, month: 12, month_day: 31, hour: 23, minute: 59, second: 59, nanoseconds: 999_999_999 };
59
60 const MIN_UNIX_TIME: i64 = UtcDateTime::MIN.unix_time();
62
63 const MAX_UNIX_TIME: i64 = UtcDateTime::MAX.unix_time();
65
66 const fn check_unix_time(unix_time: i64) -> Result<(), TzError> {
68 if Self::MIN_UNIX_TIME <= unix_time && unix_time <= Self::MAX_UNIX_TIME { Ok(()) } else { Err(TzError::OutOfRange) }
69 }
70
71 pub const fn new(year: i32, month: u8, month_day: u8, hour: u8, minute: u8, second: u8, nanoseconds: u32) -> Result<Self, TzError> {
84 if year == i32::MAX && month == 12 && month_day == 31 && hour == 23 && minute == 59 && second == 60 {
86 return Err(TzError::OutOfRange);
87 }
88
89 if let Err(error) = check_date_time_inputs(year, month, month_day, hour, minute, second, nanoseconds) {
90 return Err(TzError::DateTime(error));
91 }
92
93 Ok(Self { year, month, month_day, hour, minute, second, nanoseconds })
94 }
95
96 pub const fn from_timespec(unix_time: i64, nanoseconds: u32) -> Result<Self, TzError> {
98 let seconds = match unix_time.checked_sub(UNIX_OFFSET_SECS) {
99 Some(seconds) => seconds,
100 None => return Err(TzError::OutOfRange),
101 };
102
103 let mut remaining_days = seconds / SECONDS_PER_DAY;
104 let mut remaining_seconds = seconds % SECONDS_PER_DAY;
105 if remaining_seconds < 0 {
106 remaining_seconds += SECONDS_PER_DAY;
107 remaining_days -= 1;
108 }
109
110 let mut cycles_400_years = remaining_days / DAYS_PER_400_YEARS;
111 remaining_days %= DAYS_PER_400_YEARS;
112 if remaining_days < 0 {
113 remaining_days += DAYS_PER_400_YEARS;
114 cycles_400_years -= 1;
115 }
116
117 let cycles_100_years = min(remaining_days / DAYS_PER_100_YEARS, 3);
118 remaining_days -= cycles_100_years * DAYS_PER_100_YEARS;
119
120 let cycles_4_years = min(remaining_days / DAYS_PER_4_YEARS, 24);
121 remaining_days -= cycles_4_years * DAYS_PER_4_YEARS;
122
123 let remaining_years = min(remaining_days / DAYS_PER_NORMAL_YEAR, 3);
124 remaining_days -= remaining_years * DAYS_PER_NORMAL_YEAR;
125
126 let mut year = OFFSET_YEAR + remaining_years + cycles_4_years * 4 + cycles_100_years * 100 + cycles_400_years * 400;
127
128 let mut month = 0;
129 while month < DAY_IN_MONTHS_LEAP_YEAR_FROM_MARCH.len() {
130 let days = DAY_IN_MONTHS_LEAP_YEAR_FROM_MARCH[month];
131 if remaining_days < days {
132 break;
133 }
134 remaining_days -= days;
135 month += 1;
136 }
137 month += 2;
138
139 if month >= MONTHS_PER_YEAR as usize {
140 month -= MONTHS_PER_YEAR as usize;
141 year += 1;
142 }
143 month += 1;
144
145 let month_day = 1 + remaining_days;
146
147 let hour = remaining_seconds / SECONDS_PER_HOUR;
148 let minute = (remaining_seconds / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR;
149 let second = remaining_seconds % SECONDS_PER_MINUTE;
150
151 let year = match try_into_i32(year) {
152 Ok(year) => year,
153 Err(error) => return Err(error),
154 };
155
156 Ok(Self { year, month: month as u8, month_day: month_day as u8, hour: hour as u8, minute: minute as u8, second: second as u8, nanoseconds })
157 }
158
159 pub const fn from_total_nanoseconds(total_nanoseconds: i128) -> Result<Self, TzError> {
161 match total_nanoseconds_to_timespec(total_nanoseconds) {
162 Ok((unix_time, nanoseconds)) => Self::from_timespec(unix_time, nanoseconds),
163 Err(error) => Err(error),
164 }
165 }
166
167 pub const fn unix_time(&self) -> i64 {
169 unix_time(self.year, self.month, self.month_day, self.hour, self.minute, self.second)
170 }
171
172 pub const fn project(&self, time_zone_ref: TimeZoneRef<'_>) -> Result<DateTime, TzError> {
177 DateTime::from_timespec(self.unix_time(), self.nanoseconds, time_zone_ref)
178 }
179
180 pub const fn checked_add(&self, duration: Duration) -> Option<Self> {
182 let total_nanoseconds = self.total_nanoseconds() + duration.as_nanos() as i128;
184
185 match Self::from_total_nanoseconds(total_nanoseconds) {
186 Ok(x) => Some(x),
187 Err(_) => None,
188 }
189 }
190
191 pub const fn checked_sub(&self, duration: Duration) -> Option<Self> {
193 let total_nanoseconds = self.total_nanoseconds() - duration.as_nanos() as i128;
195
196 match Self::from_total_nanoseconds(total_nanoseconds) {
197 Ok(x) => Some(x),
198 Err(_) => None,
199 }
200 }
201
202 pub const fn duration_since(&self, earlier: Self) -> Result<Duration, Duration> {
207 let current_total_nanoseconds = self.total_nanoseconds();
208 let earlier_total_nanoseconds = earlier.total_nanoseconds();
209
210 duration_between(earlier_total_nanoseconds, current_total_nanoseconds)
211 }
212
213 #[cfg(feature = "std")]
215 pub fn now() -> Result<Self, TzError> {
216 SystemTime::now().try_into()
217 }
218}
219
220#[cfg(feature = "std")]
221impl TryFrom<SystemTime> for UtcDateTime {
222 type Error = TzError;
223
224 fn try_from(time: SystemTime) -> Result<Self, Self::Error> {
225 Self::from_total_nanoseconds(crate::utils::system_time::total_nanoseconds(time))
226 }
227}
228
229#[cfg(feature = "std")]
230impl From<UtcDateTime> for SystemTime {
231 fn from(utc_date_time: UtcDateTime) -> Self {
232 match duration_between(0, utc_date_time.total_nanoseconds()) {
233 Ok(duration) => SystemTime::UNIX_EPOCH + duration,
234 Err(duration) => SystemTime::UNIX_EPOCH - duration,
235 }
236 }
237}
238
239impl Add<Duration> for UtcDateTime {
240 type Output = UtcDateTime;
241
242 fn add(self, rhs: Duration) -> Self::Output {
248 self.checked_add(rhs).expect("attempt to add with overflow")
249 }
250}
251
252impl AddAssign<Duration> for UtcDateTime {
253 fn add_assign(&mut self, rhs: Duration) {
254 *self = *self + rhs
255 }
256}
257
258impl Sub<Duration> for UtcDateTime {
259 type Output = UtcDateTime;
260
261 fn sub(self, rhs: Duration) -> Self::Output {
267 self.checked_sub(rhs).expect("attempt to subtract with overflow")
268 }
269}
270
271impl SubAssign<Duration> for UtcDateTime {
272 fn sub_assign(&mut self, rhs: Duration) {
273 *self = *self - rhs
274 }
275}
276
277#[derive(Debug, Copy, Clone)]
279pub struct DateTime {
280 year: i32,
282 month: u8,
284 month_day: u8,
286 hour: u8,
288 minute: u8,
290 second: u8,
292 local_time_type: LocalTimeType,
294 unix_time: i64,
296 nanoseconds: u32,
298}
299
300impl PartialEq for DateTime {
301 fn eq(&self, other: &Self) -> bool {
302 (self.unix_time, self.nanoseconds) == (other.unix_time, other.nanoseconds)
303 }
304}
305
306impl PartialOrd for DateTime {
307 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
308 (self.unix_time, self.nanoseconds).partial_cmp(&(other.unix_time, other.nanoseconds))
309 }
310}
311
312impl fmt::Display for DateTime {
313 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
314 let ut_offset = self.local_time_type().ut_offset();
315 format_date_time(f, self.year, self.month, self.month_day, self.hour, self.minute, self.second, self.nanoseconds, ut_offset)
316 }
317}
318
319impl DateTime {
320 #[allow(clippy::too_many_arguments)]
334 pub const fn new(
335 year: i32,
336 month: u8,
337 month_day: u8,
338 hour: u8,
339 minute: u8,
340 second: u8,
341 nanoseconds: u32,
342 local_time_type: LocalTimeType,
343 ) -> Result<Self, TzError> {
344 if let Err(error) = check_date_time_inputs(year, month, month_day, hour, minute, second, nanoseconds) {
345 return Err(TzError::DateTime(error));
346 }
347
348 let unix_time = unix_time(year, month, month_day, hour, minute, second) - local_time_type.ut_offset() as i64;
350
351 if let Err(error) = UtcDateTime::check_unix_time(unix_time) {
353 return Err(error);
354 }
355
356 Ok(Self { year, month, month_day, hour, minute, second, local_time_type, unix_time, nanoseconds })
357 }
358
359 #[allow(clippy::too_many_arguments)]
373 #[cfg(feature = "alloc")]
374 pub fn find(
375 year: i32,
376 month: u8,
377 month_day: u8,
378 hour: u8,
379 minute: u8,
380 second: u8,
381 nanoseconds: u32,
382 time_zone_ref: TimeZoneRef<'_>,
383 ) -> Result<FoundDateTimeList, TzError> {
384 let mut found_date_time_list = FoundDateTimeList::default();
385 find_date_time(&mut found_date_time_list, year, month, month_day, hour, minute, second, nanoseconds, time_zone_ref)?;
386 Ok(found_date_time_list)
387 }
388
389 #[allow(clippy::too_many_arguments)]
441 pub fn find_n<'a>(
442 buf: &'a mut [Option<FoundDateTimeKind>],
443 year: i32,
444 month: u8,
445 month_day: u8,
446 hour: u8,
447 minute: u8,
448 second: u8,
449 nanoseconds: u32,
450 time_zone_ref: TimeZoneRef<'_>,
451 ) -> Result<FoundDateTimeListRefMut<'a>, TzError> {
452 let mut found_date_time_list = FoundDateTimeListRefMut::new(buf);
453 find_date_time(&mut found_date_time_list, year, month, month_day, hour, minute, second, nanoseconds, time_zone_ref)?;
454 Ok(found_date_time_list)
455 }
456
457 pub const fn from_timespec_and_local(unix_time: i64, nanoseconds: u32, local_time_type: LocalTimeType) -> Result<Self, TzError> {
459 let unix_time_with_offset = match unix_time.checked_add(local_time_type.ut_offset() as i64) {
460 Some(unix_time_with_offset) => unix_time_with_offset,
461 None => return Err(TzError::OutOfRange),
462 };
463
464 let utc_date_time_with_offset = match UtcDateTime::from_timespec(unix_time_with_offset, nanoseconds) {
465 Ok(utc_date_time_with_offset) => utc_date_time_with_offset,
466 Err(error) => return Err(error),
467 };
468
469 let UtcDateTime { year, month, month_day, hour, minute, second, nanoseconds } = utc_date_time_with_offset;
470 Ok(Self { year, month, month_day, hour, minute, second, local_time_type, unix_time, nanoseconds })
471 }
472
473 pub const fn from_timespec(unix_time: i64, nanoseconds: u32, time_zone_ref: TimeZoneRef<'_>) -> Result<Self, TzError> {
475 let local_time_type = match time_zone_ref.find_local_time_type(unix_time) {
476 Ok(&local_time_type) => local_time_type,
477 Err(error) => return Err(error),
478 };
479
480 Self::from_timespec_and_local(unix_time, nanoseconds, local_time_type)
481 }
482
483 pub const fn from_total_nanoseconds_and_local(total_nanoseconds: i128, local_time_type: LocalTimeType) -> Result<Self, TzError> {
485 match total_nanoseconds_to_timespec(total_nanoseconds) {
486 Ok((unix_time, nanoseconds)) => Self::from_timespec_and_local(unix_time, nanoseconds, local_time_type),
487 Err(error) => Err(error),
488 }
489 }
490
491 pub const fn from_total_nanoseconds(total_nanoseconds: i128, time_zone_ref: TimeZoneRef<'_>) -> Result<Self, TzError> {
493 match total_nanoseconds_to_timespec(total_nanoseconds) {
494 Ok((unix_time, nanoseconds)) => Self::from_timespec(unix_time, nanoseconds, time_zone_ref),
495 Err(error) => Err(error),
496 }
497 }
498
499 pub const fn project(&self, time_zone_ref: TimeZoneRef<'_>) -> Result<Self, TzError> {
504 Self::from_timespec(self.unix_time, self.nanoseconds, time_zone_ref)
505 }
506
507 pub const fn duration_since(&self, earlier: Self) -> Result<Duration, Duration> {
512 let current_total_nanoseconds = self.total_nanoseconds();
513 let earlier_total_nanoseconds = earlier.total_nanoseconds();
514
515 duration_between(earlier_total_nanoseconds, current_total_nanoseconds)
516 }
517
518 #[cfg(feature = "std")]
520 pub fn now(time_zone_ref: TimeZoneRef<'_>) -> Result<Self, TzError> {
521 let now = crate::utils::system_time::total_nanoseconds(SystemTime::now());
522 Self::from_total_nanoseconds(now, time_zone_ref)
523 }
524}
525
526impl TryFrom<DateTime> for UtcDateTime {
527 type Error = TzError;
528
529 fn try_from(date_time: DateTime) -> Result<Self, Self::Error> {
530 Self::from_timespec(date_time.unix_time, date_time.nanoseconds)
531 }
532}
533
534#[cfg(feature = "std")]
535impl From<DateTime> for SystemTime {
536 fn from(date_time: DateTime) -> Self {
537 match duration_between(0, date_time.total_nanoseconds()) {
538 Ok(duration) => SystemTime::UNIX_EPOCH + duration,
539 Err(duration) => SystemTime::UNIX_EPOCH - duration,
540 }
541 }
542}
543
544macro_rules! impl_datetime {
546 () => {
547 #[inline]
549 pub const fn year(&self) -> i32 {
550 self.year
551 }
552
553 #[inline]
555 pub const fn month(&self) -> u8 {
556 self.month
557 }
558
559 #[inline]
561 pub const fn month_day(&self) -> u8 {
562 self.month_day
563 }
564
565 #[inline]
567 pub const fn hour(&self) -> u8 {
568 self.hour
569 }
570
571 #[inline]
573 pub const fn minute(&self) -> u8 {
574 self.minute
575 }
576
577 #[inline]
579 pub const fn second(&self) -> u8 {
580 self.second
581 }
582
583 #[inline]
585 pub const fn nanoseconds(&self) -> u32 {
586 self.nanoseconds
587 }
588
589 #[inline]
591 pub const fn week_day(&self) -> u8 {
592 week_day(self.year, self.month as usize, self.month_day as i64)
593 }
594
595 #[inline]
597 pub const fn year_day(&self) -> u16 {
598 year_day(self.year, self.month as usize, self.month_day as i64)
599 }
600
601 #[inline]
603 pub const fn total_nanoseconds(&self) -> i128 {
604 nanoseconds_since_unix_epoch(self.unix_time(), self.nanoseconds)
605 }
606 };
607}
608
609impl UtcDateTime {
610 impl_datetime!();
611}
612
613impl DateTime {
614 impl_datetime!();
615
616 #[inline]
618 pub const fn local_time_type(&self) -> &LocalTimeType {
619 &self.local_time_type
620 }
621
622 #[inline]
624 pub const fn unix_time(&self) -> i64 {
625 self.unix_time
626 }
627}
628
629#[inline]
638const fn week_day(year: i32, month: usize, month_day: i64) -> u8 {
639 let days_since_unix_epoch = days_since_unix_epoch(year, month, month_day);
640 (4 + days_since_unix_epoch).rem_euclid(DAYS_PER_WEEK) as u8
641}
642
643#[inline]
652const fn year_day(year: i32, month: usize, month_day: i64) -> u16 {
653 let leap = (month >= 3 && is_leap_year(year)) as i64;
654 (CUMUL_DAYS_IN_MONTHS_NORMAL_YEAR[month - 1] + leap + month_day - 1) as u16
655}
656
657#[inline]
659pub(crate) const fn is_leap_year(year: i32) -> bool {
660 year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
661}
662
663#[inline]
674pub(crate) const fn days_since_unix_epoch(year: i32, month: usize, month_day: i64) -> i64 {
675 let is_leap_year = is_leap_year(year);
676
677 let year = year as i64;
678
679 let mut result = (year - 1970) * 365;
680
681 if year >= 1970 {
682 result += (year - 1968) / 4;
683 result -= (year - 1900) / 100;
684 result += (year - 1600) / 400;
685
686 if is_leap_year && month < 3 {
687 result -= 1;
688 }
689 } else {
690 result += (year - 1972) / 4;
691 result -= (year - 2000) / 100;
692 result += (year - 2000) / 400;
693
694 if is_leap_year && month >= 3 {
695 result += 1;
696 }
697 }
698
699 result += CUMUL_DAYS_IN_MONTHS_NORMAL_YEAR[month - 1] + month_day - 1;
700
701 result
702}
703
704#[inline]
716const fn unix_time(year: i32, month: u8, month_day: u8, hour: u8, minute: u8, second: u8) -> i64 {
717 let mut result = days_since_unix_epoch(year, month as usize, month_day as i64);
718 result *= HOURS_PER_DAY;
719 result += hour as i64;
720 result *= MINUTES_PER_HOUR;
721 result += minute as i64;
722 result *= SECONDS_PER_MINUTE;
723 result += second as i64;
724
725 result
726}
727
728#[inline]
730const fn nanoseconds_since_unix_epoch(unix_time: i64, nanoseconds: u32) -> i128 {
731 unix_time as i128 * NANOSECONDS_PER_SECOND as i128 + nanoseconds as i128
733}
734
735#[inline]
743const fn total_nanoseconds_to_timespec(total_nanoseconds: i128) -> Result<(i64, u32), TzError> {
744 let unix_time = match try_into_i64(total_nanoseconds.div_euclid(NANOSECONDS_PER_SECOND as i128)) {
745 Ok(unix_time) => unix_time,
746 Err(error) => return Err(error),
747 };
748
749 let nanoseconds = total_nanoseconds.rem_euclid(NANOSECONDS_PER_SECOND as i128) as u32;
750
751 Ok((unix_time, nanoseconds))
752}
753
754#[inline]
759const fn duration_between(before: i128, after: i128) -> Result<Duration, Duration> {
760 let total_nanoseconds_diff = after.abs_diff(before);
762
763 let secs = total_nanoseconds_diff / NANOSECONDS_PER_SECOND as u128;
764 let nanos = total_nanoseconds_diff % NANOSECONDS_PER_SECOND as u128;
765
766 let duration = Duration::new(secs as u64, nanos as u32);
768
769 if after >= before { Ok(duration) } else { Err(duration) }
770}
771
772const fn check_date_time_inputs(year: i32, month: u8, month_day: u8, hour: u8, minute: u8, second: u8, nanoseconds: u32) -> Result<(), DateTimeError> {
785 if !(1 <= month && month <= 12) {
786 return Err(DateTimeError::InvalidMonth);
787 }
788 if !(1 <= month_day && month_day <= 31) {
789 return Err(DateTimeError::InvalidMonthDay);
790 }
791 if hour > 23 {
792 return Err(DateTimeError::InvalidHour);
793 }
794 if minute > 59 {
795 return Err(DateTimeError::InvalidMinute);
796 }
797 if second > 60 {
798 return Err(DateTimeError::InvalidSecond);
799 }
800 if nanoseconds >= NANOSECONDS_PER_SECOND {
801 return Err(DateTimeError::InvalidNanoseconds);
802 }
803
804 let leap = is_leap_year(year) as i64;
805
806 let mut days_in_month = DAYS_IN_MONTHS_NORMAL_YEAR[month as usize - 1];
807 if month == 2 {
808 days_in_month += leap;
809 }
810
811 if month_day as i64 > days_in_month {
812 return Err(DateTimeError::InvalidMonthDay);
813 }
814
815 Ok(())
816}
817
818#[allow(clippy::too_many_arguments)]
833fn format_date_time(
834 f: &mut fmt::Formatter,
835 year: i32,
836 month: u8,
837 month_day: u8,
838 hour: u8,
839 minute: u8,
840 second: u8,
841 nanoseconds: u32,
842 ut_offset: i32,
843) -> fmt::Result {
844 write!(f, "{year}-{month:02}-{month_day:02}T{hour:02}:{minute:02}:{second:02}.{nanoseconds:09}")?;
845
846 if ut_offset != 0 {
847 let ut_offset = ut_offset as i64;
848 let ut_offset_abs = ut_offset.abs();
849
850 let sign = if ut_offset < 0 { '-' } else { '+' };
851
852 let offset_hour = ut_offset_abs / SECONDS_PER_HOUR;
853 let offset_minute = (ut_offset_abs / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR;
854 let offset_second = ut_offset_abs % SECONDS_PER_MINUTE;
855
856 write!(f, "{sign}{offset_hour:02}:{offset_minute:02}")?;
857
858 if offset_second != 0 {
859 write!(f, ":{offset_second:02}")?;
860 }
861 } else {
862 write!(f, "Z")?;
863 }
864
865 Ok(())
866}
867
868#[cfg(test)]
869mod tests {
870 use super::*;
871
872 #[cfg(feature = "alloc")]
873 use crate::timezone::TimeZone;
874
875 #[cfg(feature = "alloc")]
876 pub(super) fn check_equal_date_time(x: &DateTime, y: &DateTime) {
877 assert_eq!(x.year(), y.year());
878 assert_eq!(x.month(), y.month());
879 assert_eq!(x.month_day(), y.month_day());
880 assert_eq!(x.hour(), y.hour());
881 assert_eq!(x.minute(), y.minute());
882 assert_eq!(x.second(), y.second());
883 assert_eq!(x.local_time_type(), y.local_time_type());
884 assert_eq!(x.unix_time(), y.unix_time());
885 assert_eq!(x.nanoseconds(), y.nanoseconds());
886 }
887
888 #[cfg(feature = "alloc")]
889 #[test]
890 fn test_date_time() -> Result<(), TzError> {
891 let time_zone_utc = TimeZone::utc();
892 let utc = LocalTimeType::utc();
893
894 let time_zone_cet = TimeZone::fixed(3600)?;
895 let cet = LocalTimeType::with_ut_offset(3600)?;
896
897 let time_zone_eet = TimeZone::fixed(7200)?;
898 let eet = LocalTimeType::with_ut_offset(7200)?;
899
900 #[cfg(feature = "std")]
901 {
902 assert_eq!(DateTime::now(time_zone_utc.as_ref())?.local_time_type().ut_offset(), 0);
903 assert_eq!(DateTime::now(time_zone_cet.as_ref())?.local_time_type().ut_offset(), 3600);
904 assert_eq!(DateTime::now(time_zone_eet.as_ref())?.local_time_type().ut_offset(), 7200);
905 }
906
907 let unix_times = &[
908 -93750523134,
909 -11670955134,
910 -11670868734,
911 -8515195134,
912 -8483659134,
913 -8389051134,
914 -8388964734,
915 951825666,
916 951912066,
917 983448066,
918 1078056066,
919 1078142466,
920 4107585666,
921 32540356866,
922 ];
923
924 let nanoseconds_list = &[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
925
926 #[rustfmt::skip]
927 let date_times_utc = &[
928 DateTime { year: -1001, month: 3, month_day: 1, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: -93750523134, nanoseconds: 10 },
929 DateTime { year: 1600, month: 2, month_day: 29, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: -11670955134, nanoseconds: 11 },
930 DateTime { year: 1600, month: 3, month_day: 1, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: -11670868734, nanoseconds: 12 },
931 DateTime { year: 1700, month: 3, month_day: 1, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: -8515195134, nanoseconds: 13 },
932 DateTime { year: 1701, month: 3, month_day: 1, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: -8483659134, nanoseconds: 14 },
933 DateTime { year: 1704, month: 2, month_day: 29, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: -8389051134, nanoseconds: 15 },
934 DateTime { year: 1704, month: 3, month_day: 1, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: -8388964734, nanoseconds: 16 },
935 DateTime { year: 2000, month: 2, month_day: 29, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: 951825666, nanoseconds: 17 },
936 DateTime { year: 2000, month: 3, month_day: 1, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: 951912066, nanoseconds: 18 },
937 DateTime { year: 2001, month: 3, month_day: 1, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: 983448066, nanoseconds: 19 },
938 DateTime { year: 2004, month: 2, month_day: 29, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: 1078056066, nanoseconds: 20 },
939 DateTime { year: 2004, month: 3, month_day: 1, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: 1078142466, nanoseconds: 21 },
940 DateTime { year: 2100, month: 3, month_day: 1, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: 4107585666, nanoseconds: 22 },
941 DateTime { year: 3001, month: 3, month_day: 1, hour: 12, minute: 1, second: 6, local_time_type: utc, unix_time: 32540356866, nanoseconds: 23 },
942 ];
943
944 #[rustfmt::skip]
945 let date_times_cet = &[
946 DateTime { year: -1001, month: 3, month_day: 1, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: -93750523134, nanoseconds: 10 },
947 DateTime { year: 1600, month: 2, month_day: 29, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: -11670955134, nanoseconds: 11 },
948 DateTime { year: 1600, month: 3, month_day: 1, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: -11670868734, nanoseconds: 12 },
949 DateTime { year: 1700, month: 3, month_day: 1, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: -8515195134, nanoseconds: 13 },
950 DateTime { year: 1701, month: 3, month_day: 1, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: -8483659134, nanoseconds: 14 },
951 DateTime { year: 1704, month: 2, month_day: 29, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: -8389051134, nanoseconds: 15 },
952 DateTime { year: 1704, month: 3, month_day: 1, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: -8388964734, nanoseconds: 16 },
953 DateTime { year: 2000, month: 2, month_day: 29, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: 951825666, nanoseconds: 17 },
954 DateTime { year: 2000, month: 3, month_day: 1, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: 951912066, nanoseconds: 18 },
955 DateTime { year: 2001, month: 3, month_day: 1, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: 983448066, nanoseconds: 19 },
956 DateTime { year: 2004, month: 2, month_day: 29, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: 1078056066, nanoseconds: 20 },
957 DateTime { year: 2004, month: 3, month_day: 1, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: 1078142466, nanoseconds: 21 },
958 DateTime { year: 2100, month: 3, month_day: 1, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: 4107585666, nanoseconds: 22 },
959 DateTime { year: 3001, month: 3, month_day: 1, hour: 13, minute: 1, second: 6, local_time_type: cet, unix_time: 32540356866, nanoseconds: 23 },
960 ];
961
962 #[rustfmt::skip]
963 let date_times_eet = &[
964 DateTime { year: -1001, month: 3, month_day: 1, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: -93750523134, nanoseconds: 10 },
965 DateTime { year: 1600, month: 2, month_day: 29, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: -11670955134, nanoseconds: 11 },
966 DateTime { year: 1600, month: 3, month_day: 1, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: -11670868734, nanoseconds: 12 },
967 DateTime { year: 1700, month: 3, month_day: 1, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: -8515195134, nanoseconds: 13 },
968 DateTime { year: 1701, month: 3, month_day: 1, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: -8483659134, nanoseconds: 14 },
969 DateTime { year: 1704, month: 2, month_day: 29, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: -8389051134, nanoseconds: 15 },
970 DateTime { year: 1704, month: 3, month_day: 1, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: -8388964734, nanoseconds: 16 },
971 DateTime { year: 2000, month: 2, month_day: 29, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: 951825666, nanoseconds: 17 },
972 DateTime { year: 2000, month: 3, month_day: 1, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: 951912066, nanoseconds: 18 },
973 DateTime { year: 2001, month: 3, month_day: 1, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: 983448066, nanoseconds: 19 },
974 DateTime { year: 2004, month: 2, month_day: 29, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: 1078056066, nanoseconds: 20 },
975 DateTime { year: 2004, month: 3, month_day: 1, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: 1078142466, nanoseconds: 21 },
976 DateTime { year: 2100, month: 3, month_day: 1, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: 4107585666, nanoseconds: 22 },
977 DateTime { year: 3001, month: 3, month_day: 1, hour: 14, minute: 1, second: 6, local_time_type: eet, unix_time: 32540356866, nanoseconds: 23 },
978 ];
979
980 for ((((&unix_time, &nanoseconds), date_time_utc), date_time_cet), date_time_eet) in
981 unix_times.iter().zip(nanoseconds_list).zip(date_times_utc).zip(date_times_cet).zip(date_times_eet)
982 {
983 let utc_date_time = UtcDateTime::from_timespec(unix_time, nanoseconds)?;
984
985 assert_eq!(UtcDateTime::from_timespec(utc_date_time.unix_time(), nanoseconds)?, utc_date_time);
986
987 assert_eq!(utc_date_time.year(), date_time_utc.year());
988 assert_eq!(utc_date_time.month(), date_time_utc.month());
989 assert_eq!(utc_date_time.month_day(), date_time_utc.month_day());
990 assert_eq!(utc_date_time.hour(), date_time_utc.hour());
991 assert_eq!(utc_date_time.minute(), date_time_utc.minute());
992 assert_eq!(utc_date_time.second(), date_time_utc.second());
993 assert_eq!(utc_date_time.nanoseconds(), date_time_utc.nanoseconds());
994
995 assert_eq!(utc_date_time.unix_time(), unix_time);
996 assert_eq!(date_time_utc.unix_time(), unix_time);
997 assert_eq!(date_time_cet.unix_time(), unix_time);
998 assert_eq!(date_time_eet.unix_time(), unix_time);
999
1000 assert_eq!(date_time_utc, date_time_cet);
1001 assert_eq!(date_time_utc, date_time_eet);
1002
1003 check_equal_date_time(&utc_date_time.project(time_zone_utc.as_ref())?, date_time_utc);
1004 check_equal_date_time(&utc_date_time.project(time_zone_cet.as_ref())?, date_time_cet);
1005 check_equal_date_time(&utc_date_time.project(time_zone_eet.as_ref())?, date_time_eet);
1006
1007 check_equal_date_time(&date_time_utc.project(time_zone_utc.as_ref())?, date_time_utc);
1008 check_equal_date_time(&date_time_cet.project(time_zone_utc.as_ref())?, date_time_utc);
1009 check_equal_date_time(&date_time_eet.project(time_zone_utc.as_ref())?, date_time_utc);
1010
1011 check_equal_date_time(&date_time_utc.project(time_zone_cet.as_ref())?, date_time_cet);
1012 check_equal_date_time(&date_time_cet.project(time_zone_cet.as_ref())?, date_time_cet);
1013 check_equal_date_time(&date_time_eet.project(time_zone_cet.as_ref())?, date_time_cet);
1014
1015 check_equal_date_time(&date_time_utc.project(time_zone_eet.as_ref())?, date_time_eet);
1016 check_equal_date_time(&date_time_cet.project(time_zone_eet.as_ref())?, date_time_eet);
1017 check_equal_date_time(&date_time_eet.project(time_zone_eet.as_ref())?, date_time_eet);
1018 }
1019
1020 Ok(())
1021 }
1022
1023 #[cfg(feature = "alloc")]
1024 #[test]
1025 fn test_date_time_leap_seconds() -> Result<(), TzError> {
1026 let utc_date_time = UtcDateTime::new(1972, 6, 30, 23, 59, 60, 1000)?;
1027
1028 assert_eq!(UtcDateTime::from_timespec(utc_date_time.unix_time(), 1000)?, UtcDateTime::new(1972, 7, 1, 0, 0, 0, 1000)?);
1029
1030 let date_time = utc_date_time.project(TimeZone::fixed(-3600)?.as_ref())?;
1031
1032 let date_time_result = DateTime {
1033 year: 1972,
1034 month: 6,
1035 month_day: 30,
1036 hour: 23,
1037 minute: 00,
1038 second: 00,
1039 local_time_type: LocalTimeType::with_ut_offset(-3600)?,
1040 unix_time: 78796800,
1041 nanoseconds: 1000,
1042 };
1043
1044 check_equal_date_time(&date_time, &date_time_result);
1045
1046 Ok(())
1047 }
1048
1049 #[cfg(feature = "alloc")]
1050 #[test]
1051 fn test_date_time_partial_eq_partial_ord() -> Result<(), TzError> {
1052 let time_zone_utc = TimeZone::utc();
1053 let time_zone_cet = TimeZone::fixed(3600)?;
1054 let time_zone_eet = TimeZone::fixed(7200)?;
1055
1056 let utc_date_time_1 = UtcDateTime::from_timespec(1, 1)?;
1057 let utc_date_time_2 = UtcDateTime::from_timespec(2, 1)?;
1058 let utc_date_time_3 = UtcDateTime::from_timespec(3, 1)?;
1059 let utc_date_time_4 = UtcDateTime::from_timespec(3, 1000)?;
1060
1061 let date_time_utc_1 = utc_date_time_1.project(time_zone_utc.as_ref())?;
1062 let date_time_utc_2 = utc_date_time_2.project(time_zone_utc.as_ref())?;
1063 let date_time_utc_3 = utc_date_time_3.project(time_zone_utc.as_ref())?;
1064 let date_time_utc_4 = utc_date_time_4.project(time_zone_utc.as_ref())?;
1065
1066 let date_time_cet_1 = utc_date_time_1.project(time_zone_cet.as_ref())?;
1067 let date_time_cet_2 = utc_date_time_2.project(time_zone_cet.as_ref())?;
1068 let date_time_cet_3 = utc_date_time_3.project(time_zone_cet.as_ref())?;
1069 let date_time_cet_4 = utc_date_time_4.project(time_zone_cet.as_ref())?;
1070
1071 let date_time_eet_1 = utc_date_time_1.project(time_zone_eet.as_ref())?;
1072 let date_time_eet_2 = utc_date_time_2.project(time_zone_eet.as_ref())?;
1073 let date_time_eet_3 = utc_date_time_3.project(time_zone_eet.as_ref())?;
1074 let date_time_eet_4 = utc_date_time_4.project(time_zone_eet.as_ref())?;
1075
1076 assert_eq!(date_time_utc_1, date_time_cet_1);
1077 assert_eq!(date_time_utc_1, date_time_eet_1);
1078
1079 assert_eq!(date_time_utc_2, date_time_cet_2);
1080 assert_eq!(date_time_utc_2, date_time_eet_2);
1081
1082 assert_eq!(date_time_utc_3, date_time_cet_3);
1083 assert_eq!(date_time_utc_3, date_time_eet_3);
1084
1085 assert_eq!(date_time_utc_4, date_time_cet_4);
1086 assert_eq!(date_time_utc_4, date_time_eet_4);
1087
1088 assert_ne!(date_time_utc_1, date_time_utc_2);
1089 assert_ne!(date_time_utc_1, date_time_utc_3);
1090 assert_ne!(date_time_utc_1, date_time_utc_4);
1091
1092 assert_eq!(date_time_utc_1.partial_cmp(&date_time_cet_1), Some(Ordering::Equal));
1093 assert_eq!(date_time_utc_1.partial_cmp(&date_time_eet_1), Some(Ordering::Equal));
1094
1095 assert_eq!(date_time_utc_2.partial_cmp(&date_time_cet_2), Some(Ordering::Equal));
1096 assert_eq!(date_time_utc_2.partial_cmp(&date_time_eet_2), Some(Ordering::Equal));
1097
1098 assert_eq!(date_time_utc_3.partial_cmp(&date_time_cet_3), Some(Ordering::Equal));
1099 assert_eq!(date_time_utc_3.partial_cmp(&date_time_eet_3), Some(Ordering::Equal));
1100
1101 assert_eq!(date_time_utc_4.partial_cmp(&date_time_cet_4), Some(Ordering::Equal));
1102 assert_eq!(date_time_utc_4.partial_cmp(&date_time_eet_4), Some(Ordering::Equal));
1103
1104 assert_eq!(date_time_utc_1.partial_cmp(&date_time_utc_2), Some(Ordering::Less));
1105 assert_eq!(date_time_utc_2.partial_cmp(&date_time_utc_3), Some(Ordering::Less));
1106 assert_eq!(date_time_utc_3.partial_cmp(&date_time_utc_4), Some(Ordering::Less));
1107
1108 Ok(())
1109 }
1110
1111 #[test]
1112 fn test_date_time_sync_and_send() {
1113 trait _AssertSyncSendStatic: Sync + Send + 'static {}
1114 impl _AssertSyncSendStatic for DateTime {}
1115 }
1116
1117 #[test]
1118 fn test_utc_date_time_ord() -> Result<(), TzError> {
1119 let utc_date_time_1 = UtcDateTime::new(1972, 6, 30, 23, 59, 59, 1000)?;
1120 let utc_date_time_2 = UtcDateTime::new(1972, 6, 30, 23, 59, 60, 1000)?;
1121 let utc_date_time_3 = UtcDateTime::new(1972, 7, 1, 0, 0, 0, 1000)?;
1122 let utc_date_time_4 = UtcDateTime::new(1972, 7, 1, 0, 0, 0, 1001)?;
1123
1124 assert_eq!(utc_date_time_1.cmp(&utc_date_time_1), Ordering::Equal);
1125 assert_eq!(utc_date_time_1.cmp(&utc_date_time_2), Ordering::Less);
1126 assert_eq!(utc_date_time_1.cmp(&utc_date_time_3), Ordering::Less);
1127 assert_eq!(utc_date_time_1.cmp(&utc_date_time_4), Ordering::Less);
1128
1129 assert_eq!(utc_date_time_2.cmp(&utc_date_time_1), Ordering::Greater);
1130 assert_eq!(utc_date_time_2.cmp(&utc_date_time_2), Ordering::Equal);
1131 assert_eq!(utc_date_time_2.cmp(&utc_date_time_3), Ordering::Less);
1132 assert_eq!(utc_date_time_2.cmp(&utc_date_time_4), Ordering::Less);
1133
1134 assert_eq!(utc_date_time_3.cmp(&utc_date_time_1), Ordering::Greater);
1135 assert_eq!(utc_date_time_3.cmp(&utc_date_time_2), Ordering::Greater);
1136 assert_eq!(utc_date_time_3.cmp(&utc_date_time_3), Ordering::Equal);
1137 assert_eq!(utc_date_time_3.cmp(&utc_date_time_4), Ordering::Less);
1138
1139 assert_eq!(utc_date_time_4.cmp(&utc_date_time_1), Ordering::Greater);
1140 assert_eq!(utc_date_time_4.cmp(&utc_date_time_2), Ordering::Greater);
1141 assert_eq!(utc_date_time_4.cmp(&utc_date_time_3), Ordering::Greater);
1142 assert_eq!(utc_date_time_4.cmp(&utc_date_time_4), Ordering::Equal);
1143
1144 assert_eq!(utc_date_time_1.cmp(&utc_date_time_1), utc_date_time_1.unix_time().cmp(&utc_date_time_1.unix_time()));
1145 assert_eq!(utc_date_time_1.cmp(&utc_date_time_2), utc_date_time_1.unix_time().cmp(&utc_date_time_2.unix_time()));
1146 assert_eq!(utc_date_time_1.cmp(&utc_date_time_3), utc_date_time_1.unix_time().cmp(&utc_date_time_3.unix_time()));
1147 assert_eq!(utc_date_time_1.cmp(&utc_date_time_4), utc_date_time_1.unix_time().cmp(&utc_date_time_4.unix_time()));
1148
1149 assert_eq!(utc_date_time_2.cmp(&utc_date_time_1), utc_date_time_2.unix_time().cmp(&utc_date_time_1.unix_time()));
1150 assert_eq!(utc_date_time_2.cmp(&utc_date_time_2), utc_date_time_2.unix_time().cmp(&utc_date_time_2.unix_time()));
1151
1152 assert_eq!(utc_date_time_3.cmp(&utc_date_time_1), utc_date_time_3.unix_time().cmp(&utc_date_time_1.unix_time()));
1153 assert_eq!(utc_date_time_3.cmp(&utc_date_time_3), utc_date_time_3.unix_time().cmp(&utc_date_time_3.unix_time()));
1154
1155 assert_eq!(utc_date_time_4.cmp(&utc_date_time_1), utc_date_time_4.unix_time().cmp(&utc_date_time_1.unix_time()));
1156 assert_eq!(utc_date_time_4.cmp(&utc_date_time_4), utc_date_time_4.unix_time().cmp(&utc_date_time_4.unix_time()));
1157
1158 Ok(())
1159 }
1160
1161 #[cfg(feature = "alloc")]
1162 #[test]
1163 fn test_date_time_format() -> Result<(), TzError> {
1164 use alloc::string::ToString;
1165
1166 let time_zones = [
1167 TimeZone::fixed(-49550)?,
1168 TimeZone::fixed(-5400)?,
1169 TimeZone::fixed(-3600)?,
1170 TimeZone::fixed(-1800)?,
1171 TimeZone::fixed(0)?,
1172 TimeZone::fixed(1800)?,
1173 TimeZone::fixed(3600)?,
1174 TimeZone::fixed(5400)?,
1175 TimeZone::fixed(49550)?,
1176 ];
1177
1178 let utc_date_times = &[UtcDateTime::new(2000, 1, 2, 3, 4, 5, 0)?, UtcDateTime::new(2000, 1, 2, 3, 4, 5, 123_456_789)?];
1179
1180 let utc_date_time_strings = &["2000-01-02T03:04:05.000000000Z", "2000-01-02T03:04:05.123456789Z"];
1181
1182 let date_time_strings_list = &[
1183 &[
1184 "2000-01-01T13:18:15.000000000-13:45:50",
1185 "2000-01-02T01:34:05.000000000-01:30",
1186 "2000-01-02T02:04:05.000000000-01:00",
1187 "2000-01-02T02:34:05.000000000-00:30",
1188 "2000-01-02T03:04:05.000000000Z",
1189 "2000-01-02T03:34:05.000000000+00:30",
1190 "2000-01-02T04:04:05.000000000+01:00",
1191 "2000-01-02T04:34:05.000000000+01:30",
1192 "2000-01-02T16:49:55.000000000+13:45:50",
1193 ],
1194 &[
1195 "2000-01-01T13:18:15.123456789-13:45:50",
1196 "2000-01-02T01:34:05.123456789-01:30",
1197 "2000-01-02T02:04:05.123456789-01:00",
1198 "2000-01-02T02:34:05.123456789-00:30",
1199 "2000-01-02T03:04:05.123456789Z",
1200 "2000-01-02T03:34:05.123456789+00:30",
1201 "2000-01-02T04:04:05.123456789+01:00",
1202 "2000-01-02T04:34:05.123456789+01:30",
1203 "2000-01-02T16:49:55.123456789+13:45:50",
1204 ],
1205 ];
1206
1207 for ((utc_date_time, &utc_date_time_string), &date_time_strings) in utc_date_times.iter().zip(utc_date_time_strings).zip(date_time_strings_list) {
1208 for (time_zone, &date_time_string) in time_zones.iter().zip(date_time_strings) {
1209 assert_eq!(utc_date_time.to_string(), utc_date_time_string);
1210 assert_eq!(utc_date_time.project(time_zone.as_ref())?.to_string(), date_time_string);
1211 }
1212 }
1213
1214 Ok(())
1215 }
1216
1217 #[cfg(feature = "alloc")]
1218 #[test]
1219 fn test_date_time_duration() -> Result<(), TzError> {
1220 let utc_date_time = UtcDateTime::new(1, 2, 3, 4, 5, 6, 789_012_345)?;
1221 let date_time = utc_date_time.project(TimeZoneRef::utc())?;
1222
1223 let duration = Duration::new(24 * 3600 * 365, 999_999_999);
1224
1225 let added_utc_date_time = UtcDateTime::new(2, 2, 3, 4, 5, 7, 789_012_344)?;
1226 let substracted_utc_date_time = UtcDateTime::new(0, 2, 4, 4, 5, 5, 789_012_346)?;
1227
1228 assert_eq!(utc_date_time.checked_add(duration), Some(added_utc_date_time));
1229 assert_eq!(utc_date_time.checked_sub(duration), Some(substracted_utc_date_time));
1230
1231 assert_eq!(utc_date_time.duration_since(substracted_utc_date_time), Ok(duration));
1232 assert_eq!(date_time.duration_since(substracted_utc_date_time.project(TimeZoneRef::utc())?), Ok(duration));
1233
1234 Ok(())
1235 }
1236
1237 #[cfg(feature = "alloc")]
1238 #[test]
1239 fn test_date_time_overflow() -> Result<(), TzError> {
1240 assert!(UtcDateTime::new(i32::MIN, 1, 1, 0, 0, 0, 0).is_ok());
1241 assert!(UtcDateTime::new(i32::MAX, 12, 31, 23, 59, 59, 0).is_ok());
1242
1243 assert!(DateTime::new(i32::MIN, 1, 1, 0, 0, 0, 0, LocalTimeType::utc()).is_ok());
1244 assert!(DateTime::new(i32::MAX, 12, 31, 23, 59, 59, 0, LocalTimeType::utc()).is_ok());
1245
1246 assert!(matches!(DateTime::new(i32::MIN, 1, 1, 0, 0, 0, 0, LocalTimeType::with_ut_offset(1)?), Err(TzError::OutOfRange)));
1247 assert!(matches!(DateTime::new(i32::MAX, 12, 31, 23, 59, 59, 0, LocalTimeType::with_ut_offset(-1)?), Err(TzError::OutOfRange)));
1248
1249 assert!(matches!(UtcDateTime::new(i32::MAX, 12, 31, 23, 59, 60, 0), Err(TzError::OutOfRange)));
1250 assert!(matches!(DateTime::new(i32::MAX, 12, 31, 23, 59, 60, 0, LocalTimeType::utc()), Err(TzError::OutOfRange)));
1251 assert!(DateTime::new(i32::MAX, 12, 31, 23, 59, 60, 0, LocalTimeType::with_ut_offset(1)?).is_ok());
1252
1253 assert!(UtcDateTime::from_timespec(UtcDateTime::MIN_UNIX_TIME, 0).is_ok());
1254 assert!(UtcDateTime::from_timespec(UtcDateTime::MAX_UNIX_TIME, 0).is_ok());
1255
1256 assert!(matches!(UtcDateTime::from_timespec(UtcDateTime::MIN_UNIX_TIME - 1, 0), Err(TzError::OutOfRange)));
1257 assert!(matches!(UtcDateTime::from_timespec(UtcDateTime::MAX_UNIX_TIME + 1, 0), Err(TzError::OutOfRange)));
1258
1259 assert!(matches!(UtcDateTime::from_timespec(UtcDateTime::MIN_UNIX_TIME, 0)?.project(TimeZone::fixed(-1)?.as_ref()), Err(TzError::OutOfRange)));
1260 assert!(matches!(UtcDateTime::from_timespec(UtcDateTime::MAX_UNIX_TIME, 0)?.project(TimeZone::fixed(1)?.as_ref()), Err(TzError::OutOfRange)));
1261
1262 assert!(matches!(UtcDateTime::from_timespec(i64::MIN, 0), Err(TzError::OutOfRange)));
1263 assert!(matches!(UtcDateTime::from_timespec(i64::MAX, 0), Err(TzError::OutOfRange)));
1264
1265 assert!(DateTime::from_timespec(UtcDateTime::MIN_UNIX_TIME, 0, TimeZone::fixed(0)?.as_ref()).is_ok());
1266 assert!(DateTime::from_timespec(UtcDateTime::MAX_UNIX_TIME, 0, TimeZone::fixed(0)?.as_ref()).is_ok());
1267
1268 assert!(matches!(DateTime::from_timespec(i64::MIN, 0, TimeZone::fixed(-1)?.as_ref()), Err(TzError::OutOfRange)));
1269 assert!(matches!(DateTime::from_timespec(i64::MAX, 0, TimeZone::fixed(1)?.as_ref()), Err(TzError::OutOfRange)));
1270
1271 assert_eq!(UtcDateTime::MIN.checked_sub(Duration::from_nanos(1)), None);
1272 assert_eq!(UtcDateTime::MAX.checked_add(Duration::from_nanos(1)), None);
1273
1274 assert_eq!(UtcDateTime::MIN.checked_sub(Duration::MAX), None);
1275 assert_eq!(UtcDateTime::MAX.checked_add(Duration::MAX), None);
1276
1277 assert_eq!(UtcDateTime::MAX.duration_since(UtcDateTime::MIN), Ok(Duration::new(135536076801503999, 999999999)));
1278 assert_eq!(UtcDateTime::MIN.duration_since(UtcDateTime::MAX), Err(Duration::new(135536076801503999, 999999999)));
1279
1280 Ok(())
1281 }
1282
1283 #[test]
1284 fn test_week_day() {
1285 assert_eq!(week_day(1970, 1, 1), 4);
1286
1287 assert_eq!(week_day(2000, 1, 1), 6);
1288 assert_eq!(week_day(2000, 2, 28), 1);
1289 assert_eq!(week_day(2000, 2, 29), 2);
1290 assert_eq!(week_day(2000, 3, 1), 3);
1291 assert_eq!(week_day(2000, 12, 31), 0);
1292
1293 assert_eq!(week_day(2001, 1, 1), 1);
1294 assert_eq!(week_day(2001, 2, 28), 3);
1295 assert_eq!(week_day(2001, 3, 1), 4);
1296 assert_eq!(week_day(2001, 12, 31), 1);
1297 }
1298
1299 #[test]
1300 fn test_year_day() {
1301 assert_eq!(year_day(2000, 1, 1), 0);
1302 assert_eq!(year_day(2000, 2, 28), 58);
1303 assert_eq!(year_day(2000, 2, 29), 59);
1304 assert_eq!(year_day(2000, 3, 1), 60);
1305 assert_eq!(year_day(2000, 12, 31), 365);
1306
1307 assert_eq!(year_day(2001, 1, 1), 0);
1308 assert_eq!(year_day(2001, 2, 28), 58);
1309 assert_eq!(year_day(2001, 3, 1), 59);
1310 assert_eq!(year_day(2001, 12, 31), 364);
1311 }
1312
1313 #[test]
1314 fn test_is_leap_year() {
1315 assert!(is_leap_year(2000));
1316 assert!(!is_leap_year(2001));
1317 assert!(is_leap_year(2004));
1318 assert!(!is_leap_year(2100));
1319 assert!(!is_leap_year(2200));
1320 assert!(!is_leap_year(2300));
1321 assert!(is_leap_year(2400));
1322 }
1323
1324 #[test]
1325 fn test_days_since_unix_epoch() {
1326 assert_eq!(days_since_unix_epoch(-1001, 3, 1), -1085076);
1327 assert_eq!(days_since_unix_epoch(1600, 2, 29), -135081);
1328 assert_eq!(days_since_unix_epoch(1600, 3, 1), -135080);
1329 assert_eq!(days_since_unix_epoch(1700, 3, 1), -98556);
1330 assert_eq!(days_since_unix_epoch(1701, 3, 1), -98191);
1331 assert_eq!(days_since_unix_epoch(1704, 2, 29), -97096);
1332 assert_eq!(days_since_unix_epoch(2000, 2, 29), 11016);
1333 assert_eq!(days_since_unix_epoch(2000, 3, 1), 11017);
1334 assert_eq!(days_since_unix_epoch(2001, 3, 1), 11382);
1335 assert_eq!(days_since_unix_epoch(2004, 2, 29), 12477);
1336 assert_eq!(days_since_unix_epoch(2100, 3, 1), 47541);
1337 assert_eq!(days_since_unix_epoch(3001, 3, 1), 376624);
1338 }
1339
1340 #[test]
1341 fn test_nanoseconds_since_unix_epoch() {
1342 assert_eq!(nanoseconds_since_unix_epoch(1, 1000), 1_000_001_000);
1343 assert_eq!(nanoseconds_since_unix_epoch(0, 1000), 1000);
1344 assert_eq!(nanoseconds_since_unix_epoch(-1, 1000), -999_999_000);
1345 assert_eq!(nanoseconds_since_unix_epoch(-2, 1000), -1_999_999_000);
1346 }
1347
1348 #[test]
1349 fn test_total_nanoseconds_to_timespec() -> Result<(), TzError> {
1350 assert!(matches!(total_nanoseconds_to_timespec(1_000_001_000), Ok((1, 1000))));
1351 assert!(matches!(total_nanoseconds_to_timespec(1000), Ok((0, 1000))));
1352 assert!(matches!(total_nanoseconds_to_timespec(-999_999_000), Ok((-1, 1000))));
1353 assert!(matches!(total_nanoseconds_to_timespec(-1_999_999_000), Ok((-2, 1000))));
1354
1355 assert!(matches!(total_nanoseconds_to_timespec(i128::MAX), Err(TzError::OutOfRange)));
1356 assert!(matches!(total_nanoseconds_to_timespec(i128::MIN), Err(TzError::OutOfRange)));
1357
1358 let min_total_nanoseconds = -9223372036854775808000000000;
1359 let max_total_nanoseconds = 9223372036854775807999999999;
1360
1361 assert!(matches!(total_nanoseconds_to_timespec(min_total_nanoseconds), Ok((i64::MIN, 0))));
1362 assert!(matches!(total_nanoseconds_to_timespec(max_total_nanoseconds), Ok((i64::MAX, 999999999))));
1363
1364 assert!(matches!(total_nanoseconds_to_timespec(min_total_nanoseconds - 1), Err(TzError::OutOfRange)));
1365 assert!(matches!(total_nanoseconds_to_timespec(max_total_nanoseconds + 1), Err(TzError::OutOfRange)));
1366
1367 Ok(())
1368 }
1369
1370 #[test]
1371 fn test_duration_between() -> Result<(), TzError> {
1372 assert_eq!(duration_between(1_234_567_890, 1_234_567_890), Ok(Duration::ZERO));
1373 assert_eq!(duration_between(-1_000_001_000, 1_000_001_000), Ok(Duration::new(2, 2000)));
1374 assert_eq!(duration_between(1_000_001_000, -1_000_001_000), Err(Duration::new(2, 2000)));
1375
1376 assert_eq!(
1377 duration_between(UtcDateTime::MIN.total_nanoseconds(), UtcDateTime::MAX.total_nanoseconds()),
1378 Ok(Duration::new(135536076801503999, 999999999))
1379 );
1380
1381 Ok(())
1382 }
1383
1384 #[test]
1385 fn test_const() -> Result<(), TzError> {
1386 use crate::timezone::{AlternateTime, LeapSecond, MonthWeekDay, RuleDay, Transition, TransitionRule};
1387
1388 macro_rules! unwrap {
1389 ($x:expr) => {
1390 match $x {
1391 Ok(x) => x,
1392 Err(_) => panic!(),
1393 }
1394 };
1395 }
1396
1397 const TIME_ZONE_REF: TimeZoneRef<'static> = unwrap!(TimeZoneRef::new(
1398 &[
1399 Transition::new(-2334101314, 1),
1400 Transition::new(-1157283000, 2),
1401 Transition::new(-1155436200, 1),
1402 Transition::new(-880198200, 3),
1403 Transition::new(-769395600, 4),
1404 Transition::new(-765376200, 1),
1405 Transition::new(-712150200, 5),
1406 ],
1407 const {
1408 &[
1409 unwrap!(LocalTimeType::new(-37886, false, Some(b"LMT"))),
1410 unwrap!(LocalTimeType::new(-37800, false, Some(b"HST"))),
1411 unwrap!(LocalTimeType::new(-34200, true, Some(b"HDT"))),
1412 unwrap!(LocalTimeType::new(-34200, true, Some(b"HWT"))),
1413 unwrap!(LocalTimeType::new(-34200, true, Some(b"HPT"))),
1414 unwrap!(LocalTimeType::new(-36000, false, Some(b"HST"))),
1415 ]
1416 },
1417 &[
1418 LeapSecond::new(78796800, 1),
1419 LeapSecond::new(94694401, 2),
1420 LeapSecond::new(126230402, 3),
1421 LeapSecond::new(157766403, 4),
1422 LeapSecond::new(189302404, 5),
1423 LeapSecond::new(220924805, 6),
1424 ],
1425 const {
1426 &Some(TransitionRule::Alternate(unwrap!(AlternateTime::new(
1427 unwrap!(LocalTimeType::new(-36000, false, Some(b"HST"))),
1428 unwrap!(LocalTimeType::new(-34200, true, Some(b"HPT"))),
1429 RuleDay::MonthWeekDay(unwrap!(MonthWeekDay::new(10, 5, 0))),
1430 93600,
1431 RuleDay::MonthWeekDay(unwrap!(MonthWeekDay::new(3, 4, 4))),
1432 7200,
1433 ))))
1434 },
1435 ));
1436
1437 const UTC: TimeZoneRef<'static> = TimeZoneRef::utc();
1438
1439 const UNIX_EPOCH: UtcDateTime = unwrap!(UtcDateTime::from_timespec(0, 0));
1440 const UTC_DATE_TIME: UtcDateTime = unwrap!(UtcDateTime::new(2000, 1, 1, 0, 0, 0, 1000));
1441
1442 const DATE_TIME: DateTime = unwrap!(DateTime::new(2000, 1, 1, 1, 0, 0, 1000, unwrap!(LocalTimeType::with_ut_offset(3600))));
1443
1444 const DATE_TIME_1: DateTime = unwrap!(UTC_DATE_TIME.project(TIME_ZONE_REF));
1445 const DATE_TIME_2: DateTime = unwrap!(DATE_TIME_1.project(UTC));
1446
1447 const LOCAL_TIME_TYPE_1: &LocalTimeType = DATE_TIME_1.local_time_type();
1448 const LOCAL_TIME_TYPE_2: &LocalTimeType = DATE_TIME_2.local_time_type();
1449
1450 assert_eq!(UNIX_EPOCH.unix_time(), 0);
1451 assert_eq!(DATE_TIME.unix_time(), UTC_DATE_TIME.unix_time());
1452 assert_eq!(DATE_TIME_2.unix_time(), UTC_DATE_TIME.unix_time());
1453 assert_eq!(DATE_TIME_2.nanoseconds(), UTC_DATE_TIME.nanoseconds());
1454
1455 let date_time = UTC_DATE_TIME.project(TIME_ZONE_REF)?;
1456 assert_eq!(date_time.local_time_type().time_zone_designation(), LOCAL_TIME_TYPE_1.time_zone_designation());
1457
1458 let date_time_1 = DateTime::from_timespec(UTC_DATE_TIME.unix_time(), 1000, TIME_ZONE_REF)?;
1459 let date_time_2 = date_time_1.project(UTC)?;
1460
1461 assert_eq!(date_time, DATE_TIME_1);
1462 assert_eq!(date_time_1, DATE_TIME_1);
1463 assert_eq!(date_time_2, DATE_TIME_2);
1464
1465 let local_time_type_1 = date_time_1.local_time_type();
1466 let local_time_type_2 = date_time_2.local_time_type();
1467
1468 assert_eq!(local_time_type_1.ut_offset(), LOCAL_TIME_TYPE_1.ut_offset());
1469 assert_eq!(local_time_type_1.is_dst(), LOCAL_TIME_TYPE_1.is_dst());
1470 assert_eq!(local_time_type_1.time_zone_designation(), LOCAL_TIME_TYPE_1.time_zone_designation());
1471
1472 assert_eq!(local_time_type_2.ut_offset(), LOCAL_TIME_TYPE_2.ut_offset());
1473 assert_eq!(local_time_type_2.is_dst(), LOCAL_TIME_TYPE_2.is_dst());
1474 assert_eq!(local_time_type_2.time_zone_designation(), LOCAL_TIME_TYPE_2.time_zone_designation());
1475
1476 Ok(())
1477 }
1478}