Skip to main content

ng_oxigraph/oxsdatatypes/
date_time.rs

1#![allow(clippy::expect_used)]
2
3use crate::oxsdatatypes::{DayTimeDuration, Decimal, Duration, YearMonthDuration};
4use serde::{Deserialize, Serialize};
5use std::cmp::{min, Ordering};
6use std::fmt;
7use std::hash::{Hash, Hasher};
8use std::str::FromStr;
9
10/// [XML Schema `dateTime` datatype](https://www.w3.org/TR/xmlschema11-2/#dateTime)
11///
12/// It encodes the value using a number of seconds from the Gregorian calendar era using a [`Decimal`]
13/// and an optional timezone offset in minutes.
14#[derive(Eq, PartialEq, PartialOrd, Debug, Clone, Copy, Hash, Serialize, Deserialize)]
15pub struct DateTime {
16    timestamp: Timestamp,
17}
18
19impl DateTime {
20    pub const MAX: Self = Self {
21        timestamp: Timestamp::MAX,
22    };
23    pub const MIN: Self = Self {
24        timestamp: Timestamp::MIN,
25    };
26
27    #[inline]
28    pub(super) fn new(
29        year: i64,
30        month: u8,
31        day: u8,
32        hour: u8,
33        minute: u8,
34        second: Decimal,
35        timezone_offset: Option<TimezoneOffset>,
36    ) -> Result<Self, DateTimeOverflowError> {
37        Ok(Self {
38            timestamp: Timestamp::new(&DateTimeSevenPropertyModel {
39                year: Some(year),
40                month: Some(month),
41                day: Some(day),
42                hour: Some(hour),
43                minute: Some(minute),
44                second: Some(second),
45                timezone_offset,
46            })?,
47        })
48    }
49
50    /// [fn:current-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-current-dateTime)
51    #[inline]
52    pub fn now() -> Self {
53        Self {
54            timestamp: Timestamp::now(),
55        }
56    }
57
58    #[inline]
59    #[must_use]
60    pub fn from_be_bytes(bytes: [u8; 18]) -> Self {
61        Self {
62            timestamp: Timestamp::from_be_bytes(bytes),
63        }
64    }
65
66    /// [fn:year-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-year-from-dateTime)
67    #[inline]
68    #[must_use]
69    pub fn year(self) -> i64 {
70        self.timestamp.year()
71    }
72
73    /// [fn:month-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-month-from-dateTime)
74    #[inline]
75    #[must_use]
76    pub fn month(self) -> u8 {
77        self.timestamp.month()
78    }
79
80    /// [fn:day-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-day-from-dateTime)
81    #[inline]
82    #[must_use]
83    pub fn day(self) -> u8 {
84        self.timestamp.day()
85    }
86
87    /// [fn:hour-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-hours-from-dateTime)
88    #[inline]
89    #[must_use]
90    pub fn hour(self) -> u8 {
91        self.timestamp.hour()
92    }
93
94    /// [fn:minute-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-minutes-from-dateTime)
95    #[inline]
96    #[must_use]
97    pub fn minute(self) -> u8 {
98        self.timestamp.minute()
99    }
100
101    /// [fn:second-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-seconds-from-dateTime)
102    #[inline]
103    #[must_use]
104    pub fn second(self) -> Decimal {
105        self.timestamp.second()
106    }
107
108    /// [fn:timezone-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-timezone-from-dateTime)
109    #[inline]
110    #[must_use]
111    pub fn timezone(self) -> Option<DayTimeDuration> {
112        Some(self.timezone_offset()?.into())
113    }
114
115    #[inline]
116    #[must_use]
117    pub fn timezone_offset(self) -> Option<TimezoneOffset> {
118        self.timestamp.timezone_offset()
119    }
120
121    #[inline]
122    fn properties(self) -> DateTimeSevenPropertyModel {
123        DateTimeSevenPropertyModel {
124            year: Some(self.year()),
125            month: Some(self.month()),
126            day: Some(self.day()),
127            hour: Some(self.hour()),
128            minute: Some(self.minute()),
129            second: Some(self.second()),
130            timezone_offset: self.timezone_offset(),
131        }
132    }
133
134    #[inline]
135    #[must_use]
136    pub fn to_be_bytes(self) -> [u8; 18] {
137        self.timestamp.to_be_bytes()
138    }
139
140    /// [op:subtract-dateTimes](https://www.w3.org/TR/xpath-functions-31/#func-subtract-dateTimes)
141    ///
142    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
143    #[inline]
144    #[must_use]
145    pub fn checked_sub(self, rhs: impl Into<Self>) -> Option<DayTimeDuration> {
146        self.timestamp.checked_sub(rhs.into().timestamp)
147    }
148
149    /// [op:add-yearMonthDuration-to-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-add-yearMonthDuration-to-dateTime)
150    ///
151    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
152    #[inline]
153    #[must_use]
154    pub fn checked_add_year_month_duration(
155        self,
156        rhs: impl Into<YearMonthDuration>,
157    ) -> Option<Self> {
158        self.checked_add_duration(Duration::from(rhs.into()))
159    }
160
161    /// [op:add-dayTimeDuration-to-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-add-dayTimeDuration-to-dateTime)
162    ///
163    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
164    #[inline]
165    #[must_use]
166    pub fn checked_add_day_time_duration(self, rhs: impl Into<Duration>) -> Option<Self> {
167        let rhs = rhs.into();
168        Some(Self {
169            timestamp: self.timestamp.checked_add_seconds(rhs.all_seconds())?,
170        })
171    }
172
173    /// [op:add-yearMonthDuration-to-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-add-yearMonthDuration-to-dateTime) and [op:add-dayTimeDuration-to-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-add-dayTimeDuration-to-dateTime)
174    ///
175    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
176    #[inline]
177    #[must_use]
178    pub fn checked_add_duration(self, rhs: impl Into<Duration>) -> Option<Self> {
179        let rhs = rhs.into();
180        if let Ok(rhs) = DayTimeDuration::try_from(rhs) {
181            self.checked_add_day_time_duration(rhs)
182        } else {
183            Some(Self {
184                timestamp: Timestamp::new(&date_time_plus_duration(rhs, &self.properties())?)
185                    .ok()?,
186            })
187        }
188    }
189
190    /// [op:subtract-yearMonthDuration-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-subtract-yearMonthDuration-from-dateTime)
191    ///
192    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
193    #[inline]
194    #[must_use]
195    pub fn checked_sub_year_month_duration(
196        self,
197        rhs: impl Into<YearMonthDuration>,
198    ) -> Option<Self> {
199        self.checked_sub_duration(Duration::from(rhs.into()))
200    }
201
202    /// [op:subtract-dayTimeDuration-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-subtract-dayTimeDuration-from-dateTime)
203    ///
204    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
205    #[inline]
206    #[must_use]
207    pub fn checked_sub_day_time_duration(self, rhs: impl Into<DayTimeDuration>) -> Option<Self> {
208        let rhs = rhs.into();
209        Some(Self {
210            timestamp: self.timestamp.checked_sub_seconds(rhs.as_seconds())?,
211        })
212    }
213
214    /// [op:subtract-yearMonthDuration-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-subtract-yearMonthDuration-from-dateTime) and [op:subtract-dayTimeDuration-from-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-subtract-dayTimeDuration-from-dateTime)
215    ///
216    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
217    #[inline]
218    #[must_use]
219    pub fn checked_sub_duration(self, rhs: impl Into<Duration>) -> Option<Self> {
220        let rhs = rhs.into();
221        if let Ok(rhs) = DayTimeDuration::try_from(rhs) {
222            self.checked_sub_day_time_duration(rhs)
223        } else {
224            Some(Self {
225                timestamp: Timestamp::new(&date_time_plus_duration(
226                    rhs.checked_neg()?,
227                    &self.properties(),
228                )?)
229                .ok()?,
230            })
231        }
232    }
233
234    /// [fn:adjust-dateTime-to-timezone](https://www.w3.org/TR/xpath-functions-31/#func-adjust-dateTime-to-timezone)
235    ///
236    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
237    #[inline]
238    #[must_use]
239    pub fn adjust(self, timezone_offset: Option<TimezoneOffset>) -> Option<Self> {
240        Some(Self {
241            timestamp: self.timestamp.adjust(timezone_offset)?,
242        })
243    }
244
245    /// Checks if the two values are [identical](https://www.w3.org/TR/xmlschema11-2/#identity).
246    #[inline]
247    #[must_use]
248    pub fn is_identical_with(self, other: Self) -> bool {
249        self.timestamp.is_identical_with(other.timestamp)
250    }
251}
252
253/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
254impl TryFrom<Date> for DateTime {
255    type Error = DateTimeOverflowError;
256
257    #[inline]
258    fn try_from(date: Date) -> Result<Self, Self::Error> {
259        Self::new(
260            date.year(),
261            date.month(),
262            date.day(),
263            0,
264            0,
265            Decimal::default(),
266            date.timezone_offset(),
267        )
268    }
269}
270
271impl FromStr for DateTime {
272    type Err = ParseDateTimeError;
273
274    fn from_str(input: &str) -> Result<Self, Self::Err> {
275        ensure_complete(input, date_time_lexical_rep)
276    }
277}
278
279impl fmt::Display for DateTime {
280    #[inline]
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        let year = self.year();
283        if year < 0 {
284            f.write_str("-")?;
285        }
286        let second = self.second();
287        write!(
288            f,
289            "{:04}-{:02}-{:02}T{:02}:{:02}:{}{}",
290            year.abs(),
291            self.month(),
292            self.day(),
293            self.hour(),
294            self.minute(),
295            if Decimal::from(-10) < second && second < Decimal::from(10) {
296                "0"
297            } else {
298                ""
299            },
300            second
301        )?;
302        if let Some(timezone_offset) = self.timezone_offset() {
303            write!(f, "{timezone_offset}")?;
304        }
305        Ok(())
306    }
307}
308
309/// [XML Schema `time` datatype](https://www.w3.org/TR/xmlschema11-2/#time)
310///
311/// It encodes the value using a number of seconds from the Gregorian calendar era using a [`Decimal`],
312/// when combined with the date 1972-12-31, and an optional timezone offset in minutes.
313#[derive(Eq, PartialEq, PartialOrd, Debug, Clone, Copy, Hash)]
314pub struct Time {
315    timestamp: Timestamp,
316}
317
318impl Time {
319    #[cfg(test)]
320    const MAX: Self = Self {
321        timestamp: Timestamp {
322            value: Decimal::new_from_i128_unchecked(62_230_255_200),
323            timezone_offset: Some(TimezoneOffset::MIN),
324        },
325    };
326    #[cfg(test)]
327    const MIN: Self = Self {
328        timestamp: Timestamp {
329            value: Decimal::new_from_i128_unchecked(62_230_154_400),
330            timezone_offset: Some(TimezoneOffset::MAX),
331        },
332    };
333
334    #[inline]
335    fn new(
336        mut hour: u8,
337        minute: u8,
338        second: Decimal,
339        timezone_offset: Option<TimezoneOffset>,
340    ) -> Result<Self, DateTimeOverflowError> {
341        if hour == 24 && minute == 0 && second == Decimal::default() {
342            hour = 0;
343        }
344        Ok(Self {
345            timestamp: Timestamp::new(&DateTimeSevenPropertyModel {
346                year: None,
347                month: None,
348                day: None,
349                hour: Some(hour),
350                minute: Some(minute),
351                second: Some(second),
352                timezone_offset,
353            })?,
354        })
355    }
356
357    #[inline]
358    #[must_use]
359    pub fn from_be_bytes(bytes: [u8; 18]) -> Self {
360        Self {
361            timestamp: Timestamp::from_be_bytes(bytes),
362        }
363    }
364
365    /// [fn:current-time](https://www.w3.org/TR/xpath-functions-31/#func-current-time)
366    #[inline]
367    pub fn now() -> Self {
368        Self {
369            timestamp: Timestamp::now(),
370        }
371    }
372
373    /// [fn:hour-from-time](https://www.w3.org/TR/xpath-functions-31/#func-hours-from-time)
374    #[inline]
375    #[must_use]
376    pub fn hour(self) -> u8 {
377        self.timestamp.hour()
378    }
379
380    /// [fn:minute-from-time](https://www.w3.org/TR/xpath-functions-31/#func-minutes-from-time)
381    #[inline]
382    #[must_use]
383    pub fn minute(self) -> u8 {
384        self.timestamp.minute()
385    }
386
387    /// [fn:second-from-time](https://www.w3.org/TR/xpath-functions-31/#func-seconds-from-time)
388    #[inline]
389    #[must_use]
390    pub fn second(self) -> Decimal {
391        self.timestamp.second()
392    }
393
394    /// [fn:timezone-from-time](https://www.w3.org/TR/xpath-functions-31/#func-timezone-from-time)
395    #[inline]
396    #[must_use]
397    pub fn timezone(self) -> Option<DayTimeDuration> {
398        Some(self.timezone_offset()?.into())
399    }
400
401    #[inline]
402    #[must_use]
403    pub fn timezone_offset(self) -> Option<TimezoneOffset> {
404        self.timestamp.timezone_offset()
405    }
406
407    #[inline]
408    #[must_use]
409    pub fn to_be_bytes(self) -> [u8; 18] {
410        self.timestamp.to_be_bytes()
411    }
412
413    /// [op:subtract-times](https://www.w3.org/TR/xpath-functions-31/#func-subtract-times)
414    ///
415    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
416    #[inline]
417    #[must_use]
418    pub fn checked_sub(self, rhs: impl Into<Self>) -> Option<DayTimeDuration> {
419        self.timestamp.checked_sub(rhs.into().timestamp)
420    }
421
422    /// [op:add-dayTimeDuration-to-time](https://www.w3.org/TR/xpath-functions-31/#func-add-dayTimeDuration-to-time)
423    ///
424    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
425    #[inline]
426    #[must_use]
427    pub fn checked_add_day_time_duration(self, rhs: impl Into<DayTimeDuration>) -> Option<Self> {
428        self.checked_add_duration(Duration::from(rhs.into()))
429    }
430
431    /// [op:add-dayTimeDuration-to-time](https://www.w3.org/TR/xpath-functions-31/#func-add-dayTimeDuration-to-time)
432    ///
433    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
434    #[inline]
435    #[must_use]
436    pub fn checked_add_duration(self, rhs: impl Into<Duration>) -> Option<Self> {
437        Some(
438            DateTime::new(
439                1972,
440                12,
441                31,
442                self.hour(),
443                self.minute(),
444                self.second(),
445                self.timezone_offset(),
446            )
447            .ok()?
448            .checked_add_duration(rhs)?
449            .into(),
450        )
451    }
452
453    /// [op:subtract-dayTimeDuration-from-time](https://www.w3.org/TR/xpath-functions-31/#func-subtract-dayTimeDuration-from-time)
454    ///
455    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
456    #[inline]
457    #[must_use]
458    pub fn checked_sub_day_time_duration(self, rhs: impl Into<DayTimeDuration>) -> Option<Self> {
459        self.checked_sub_duration(Duration::from(rhs.into()))
460    }
461
462    /// [op:subtract-dayTimeDuration-from-time](https://www.w3.org/TR/xpath-functions-31/#func-subtract-dayTimeDuration-from-time)
463    ///
464    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
465    #[inline]
466    #[must_use]
467    pub fn checked_sub_duration(self, rhs: impl Into<Duration>) -> Option<Self> {
468        Some(
469            DateTime::new(
470                1972,
471                12,
472                31,
473                self.hour(),
474                self.minute(),
475                self.second(),
476                self.timezone_offset(),
477            )
478            .ok()?
479            .checked_sub_duration(rhs)?
480            .into(),
481        )
482    }
483
484    // [fn:adjust-time-to-timezone](https://www.w3.org/TR/xpath-functions-31/#func-adjust-time-to-timezone)
485    #[inline]
486    #[must_use]
487    pub fn adjust(self, timezone_offset: Option<TimezoneOffset>) -> Option<Self> {
488        Some(
489            DateTime::new(
490                1972,
491                12,
492                31,
493                self.hour(),
494                self.minute(),
495                self.second(),
496                self.timezone_offset(),
497            )
498            .ok()?
499            .adjust(timezone_offset)?
500            .into(),
501        )
502    }
503
504    /// Checks if the two values are [identical](https://www.w3.org/TR/xmlschema11-2/#identity).
505    #[inline]
506    #[must_use]
507    pub fn is_identical_with(self, other: Self) -> bool {
508        self.timestamp.is_identical_with(other.timestamp)
509    }
510}
511
512/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
513impl From<DateTime> for Time {
514    #[inline]
515    fn from(date_time: DateTime) -> Self {
516        Self::new(
517            date_time.hour(),
518            date_time.minute(),
519            date_time.second(),
520            date_time.timezone_offset(),
521        )
522        .expect("Casting from xsd:dateTime to xsd:date can't fail")
523    }
524}
525
526impl FromStr for Time {
527    type Err = ParseDateTimeError;
528
529    fn from_str(input: &str) -> Result<Self, Self::Err> {
530        ensure_complete(input, time_lexical_rep)
531    }
532}
533
534impl fmt::Display for Time {
535    #[inline]
536    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537        let second = self.second();
538        write!(
539            f,
540            "{:02}:{:02}:{}{}",
541            self.hour(),
542            self.minute(),
543            if Decimal::from(-10) < second && second < Decimal::from(10) {
544                "0"
545            } else {
546                ""
547            },
548            second
549        )?;
550        if let Some(timezone_offset) = self.timezone_offset() {
551            write!(f, "{timezone_offset}")?;
552        }
553        Ok(())
554    }
555}
556
557/// [XML Schema `date` datatype](https://www.w3.org/TR/xmlschema11-2/#date)
558///
559/// It encodes the value using a number of seconds from the Gregorian calendar era using a [`Decimal`],
560/// when combined with the time 00:00:00, and an optional timezone offset in minutes.
561#[derive(Eq, PartialEq, PartialOrd, Debug, Clone, Copy, Hash)]
562pub struct Date {
563    timestamp: Timestamp,
564}
565
566impl Date {
567    pub const MAX: Self = Self {
568        timestamp: Timestamp {
569            value: Decimal::new_from_i128_unchecked(170_141_183_460_469_216_800),
570            timezone_offset: Some(TimezoneOffset::MAX),
571        },
572    };
573    pub const MIN: Self = Self {
574        timestamp: Timestamp {
575            value: Decimal::new_from_i128_unchecked(-170_141_183_460_469_216_800),
576            timezone_offset: Some(TimezoneOffset::MIN),
577        },
578    };
579
580    #[inline]
581    fn new(
582        year: i64,
583        month: u8,
584        day: u8,
585        timezone_offset: Option<TimezoneOffset>,
586    ) -> Result<Self, DateTimeOverflowError> {
587        Ok(Self {
588            timestamp: Timestamp::new(&DateTimeSevenPropertyModel {
589                year: Some(year),
590                month: Some(month),
591                day: Some(day),
592                hour: None,
593                minute: None,
594                second: None,
595                timezone_offset,
596            })?,
597        })
598    }
599
600    #[inline]
601    #[must_use]
602    pub fn from_be_bytes(bytes: [u8; 18]) -> Self {
603        Self {
604            timestamp: Timestamp::from_be_bytes(bytes),
605        }
606    }
607
608    /// [fn:current-date](https://www.w3.org/TR/xpath-functions-31/#func-current-date)
609    #[inline]
610    pub fn now() -> Self {
611        DateTime::now()
612            .try_into()
613            .expect("The current time seems way in the future, it's strange")
614    }
615
616    /// [fn:year-from-date](https://www.w3.org/TR/xpath-functions-31/#func-year-from-date)
617    #[inline]
618    #[must_use]
619    pub fn year(self) -> i64 {
620        self.timestamp.year()
621    }
622
623    /// [fn:month-from-date](https://www.w3.org/TR/xpath-functions-31/#func-month-from-date)
624    #[inline]
625    #[must_use]
626    pub fn month(self) -> u8 {
627        self.timestamp.month()
628    }
629
630    /// [fn:day-from-date](https://www.w3.org/TR/xpath-functions-31/#func-day-from-date)
631    #[inline]
632    #[must_use]
633    pub fn day(self) -> u8 {
634        self.timestamp.day()
635    }
636
637    /// [fn:timezone-from-date](https://www.w3.org/TR/xpath-functions-31/#func-timezone-from-date)
638    #[inline]
639    #[must_use]
640    pub fn timezone(self) -> Option<DayTimeDuration> {
641        Some(self.timezone_offset()?.into())
642    }
643
644    #[inline]
645    #[must_use]
646    pub fn timezone_offset(self) -> Option<TimezoneOffset> {
647        self.timestamp.timezone_offset()
648    }
649
650    #[inline]
651    #[must_use]
652    pub fn to_be_bytes(self) -> [u8; 18] {
653        self.timestamp.to_be_bytes()
654    }
655
656    /// [op:subtract-dates](https://www.w3.org/TR/xpath-functions-31/#func-subtract-dates)
657    ///
658    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
659    #[inline]
660    #[must_use]
661    pub fn checked_sub(self, rhs: impl Into<Self>) -> Option<DayTimeDuration> {
662        self.timestamp.checked_sub(rhs.into().timestamp)
663    }
664
665    /// [op:add-yearMonthDuration-to-date](https://www.w3.org/TR/xpath-functions-31/#func-add-yearMonthDuration-to-date)
666    ///
667    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
668    #[inline]
669    #[must_use]
670    pub fn checked_add_year_month_duration(
671        self,
672        rhs: impl Into<YearMonthDuration>,
673    ) -> Option<Self> {
674        self.checked_add_duration(Duration::from(rhs.into()))
675    }
676
677    /// [op:add-dayTimeDuration-to-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-add-dayTimeDuration-to-date)
678    ///
679    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
680    #[inline]
681    #[must_use]
682    pub fn checked_add_day_time_duration(self, rhs: impl Into<DayTimeDuration>) -> Option<Self> {
683        self.checked_add_duration(Duration::from(rhs.into()))
684    }
685
686    /// [op:add-yearMonthDuration-to-date](https://www.w3.org/TR/xpath-functions-31/#func-add-yearMonthDuration-to-date) and [op:add-dayTimeDuration-to-dateTime](https://www.w3.org/TR/xpath-functions-31/#func-add-dayTimeDuration-to-date)
687    ///
688    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
689    #[inline]
690    #[must_use]
691    pub fn checked_add_duration(self, rhs: impl Into<Duration>) -> Option<Self> {
692        DateTime::try_from(self)
693            .ok()?
694            .checked_add_duration(rhs)?
695            .try_into()
696            .ok()
697    }
698
699    /// [op:subtract-yearMonthDuration-from-date](https://www.w3.org/TR/xpath-functions-31/#func-subtract-yearMonthDuration-from-date)
700    ///
701    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
702    #[inline]
703    #[must_use]
704    pub fn checked_sub_year_month_duration(
705        self,
706        rhs: impl Into<YearMonthDuration>,
707    ) -> Option<Self> {
708        self.checked_sub_duration(Duration::from(rhs.into()))
709    }
710
711    /// [op:subtract-dayTimeDuration-from-date](https://www.w3.org/TR/xpath-functions-31/#func-subtract-dayTimeDuration-from-date)
712    ///
713    /// Returns `None` in case of overflow ([`FODT0001`](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001)).
714    #[inline]
715    #[must_use]
716    pub fn checked_sub_day_time_duration(self, rhs: impl Into<DayTimeDuration>) -> Option<Self> {
717        self.checked_sub_duration(Duration::from(rhs.into()))
718    }
719
720    /// [op:subtract-yearMonthDuration-from-date](https://www.w3.org/TR/xpath-functions-31/#func-subtract-yearMonthDuration-from-date) and [op:subtract-dayTimeDuration-from-date](https://www.w3.org/TR/xpath-functions-31/#func-subtract-dayTimeDuration-from-date)
721    #[inline]
722    #[must_use]
723    pub fn checked_sub_duration(self, rhs: impl Into<Duration>) -> Option<Self> {
724        DateTime::try_from(self)
725            .ok()?
726            .checked_sub_duration(rhs)?
727            .try_into()
728            .ok()
729    }
730
731    // [fn:adjust-date-to-timezone](https://www.w3.org/TR/xpath-functions-31/#func-adjust-date-to-timezone)
732    #[inline]
733    #[must_use]
734    pub fn adjust(self, timezone_offset: Option<TimezoneOffset>) -> Option<Self> {
735        DateTime::new(
736            self.year(),
737            self.month(),
738            self.day(),
739            0,
740            0,
741            Decimal::default(),
742            self.timezone_offset(),
743        )
744        .ok()?
745        .adjust(timezone_offset)?
746        .try_into()
747        .ok()
748    }
749
750    /// Checks if the two values are [identical](https://www.w3.org/TR/xmlschema11-2/#identity).
751    #[inline]
752    #[must_use]
753    pub fn is_identical_with(self, other: Self) -> bool {
754        self.timestamp.is_identical_with(other.timestamp)
755    }
756}
757
758/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
759impl TryFrom<DateTime> for Date {
760    type Error = DateTimeOverflowError;
761
762    #[inline]
763    fn try_from(date_time: DateTime) -> Result<Self, Self::Error> {
764        Self::new(
765            date_time.year(),
766            date_time.month(),
767            date_time.day(),
768            date_time.timezone_offset(),
769        )
770    }
771}
772
773impl FromStr for Date {
774    type Err = ParseDateTimeError;
775
776    fn from_str(input: &str) -> Result<Self, Self::Err> {
777        ensure_complete(input, date_lexical_rep)
778    }
779}
780
781impl fmt::Display for Date {
782    #[inline]
783    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
784        let year = self.year();
785        if year < 0 {
786            f.write_str("-")?;
787        }
788        write!(f, "{:04}-{:02}-{:02}", year.abs(), self.month(), self.day())?;
789        if let Some(timezone_offset) = self.timezone_offset() {
790            write!(f, "{timezone_offset}")?;
791        }
792        Ok(())
793    }
794}
795
796/// [XML Schema `gYearMonth` datatype](https://www.w3.org/TR/xmlschema11-2/#gYearMonth)
797///
798/// It encodes the value using a number of seconds from the Gregorian calendar era using a [`Decimal`],
799/// when combined with the day-time 31T00:00:00, and an optional timezone offset in minutes.
800#[derive(Eq, PartialEq, PartialOrd, Debug, Clone, Copy, Hash)]
801pub struct GYearMonth {
802    timestamp: Timestamp,
803}
804
805impl GYearMonth {
806    pub const MAX: Self = Self {
807        timestamp: Timestamp {
808            value: Decimal::new_from_i128_unchecked(170_141_183_460_469_216_800),
809            timezone_offset: Some(TimezoneOffset::MAX),
810        },
811    };
812    pub const MIN: Self = Self {
813        timestamp: Timestamp {
814            value: Decimal::new_from_i128_unchecked(-170_141_183_460_466_970_400),
815            timezone_offset: Some(TimezoneOffset::MIN),
816        },
817    };
818
819    #[inline]
820    fn new(
821        year: i64,
822        month: u8,
823        timezone_offset: Option<TimezoneOffset>,
824    ) -> Result<Self, DateTimeOverflowError> {
825        Ok(Self {
826            timestamp: Timestamp::new(&DateTimeSevenPropertyModel {
827                year: Some(year),
828                month: Some(month),
829                day: None,
830                hour: None,
831                minute: None,
832                second: None,
833                timezone_offset,
834            })?,
835        })
836    }
837
838    #[inline]
839    #[must_use]
840    pub fn from_be_bytes(bytes: [u8; 18]) -> Self {
841        Self {
842            timestamp: Timestamp::from_be_bytes(bytes),
843        }
844    }
845
846    #[inline]
847    #[must_use]
848    pub fn year(self) -> i64 {
849        self.timestamp.year()
850    }
851
852    #[inline]
853    #[must_use]
854    pub fn month(self) -> u8 {
855        self.timestamp.month()
856    }
857
858    #[inline]
859    #[must_use]
860    pub fn timezone(self) -> Option<DayTimeDuration> {
861        Some(self.timezone_offset()?.into())
862    }
863
864    #[inline]
865    #[must_use]
866    pub fn timezone_offset(self) -> Option<TimezoneOffset> {
867        self.timestamp.timezone_offset()
868    }
869
870    #[inline]
871    #[must_use]
872    pub fn adjust(self, timezone_offset: Option<TimezoneOffset>) -> Option<Self> {
873        Some(Self {
874            timestamp: self.timestamp.adjust(timezone_offset)?,
875        })
876    }
877
878    #[inline]
879    #[must_use]
880    pub fn to_be_bytes(self) -> [u8; 18] {
881        self.timestamp.to_be_bytes()
882    }
883
884    /// Checks if the two values are [identical](https://www.w3.org/TR/xmlschema11-2/#identity).
885    #[inline]
886    #[must_use]
887    pub fn is_identical_with(self, other: Self) -> bool {
888        self.timestamp.is_identical_with(other.timestamp)
889    }
890}
891
892/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
893impl TryFrom<DateTime> for GYearMonth {
894    type Error = DateTimeOverflowError;
895
896    #[inline]
897    fn try_from(date_time: DateTime) -> Result<Self, Self::Error> {
898        Self::new(
899            date_time.year(),
900            date_time.month(),
901            date_time.timezone_offset(),
902        )
903    }
904}
905
906/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
907impl From<Date> for GYearMonth {
908    #[inline]
909    fn from(date: Date) -> Self {
910        Self::new(date.year(), date.month(), date.timezone_offset())
911            .expect("Casting from xsd:date to xsd:gYearMonth can't fail")
912    }
913}
914
915impl FromStr for GYearMonth {
916    type Err = ParseDateTimeError;
917
918    fn from_str(input: &str) -> Result<Self, Self::Err> {
919        ensure_complete(input, g_year_month_lexical_rep)
920    }
921}
922
923impl fmt::Display for GYearMonth {
924    #[inline]
925    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
926        let year = self.year();
927        if year < 0 {
928            f.write_str("-")?;
929        }
930        write!(f, "{:04}-{:02}", year.abs(), self.month())?;
931        if let Some(timezone_offset) = self.timezone_offset() {
932            write!(f, "{timezone_offset}")?;
933        }
934        Ok(())
935    }
936}
937
938/// [XML Schema `gYear` datatype](https://www.w3.org/TR/xmlschema11-2/#gYear)
939///
940/// It encodes the value using a number of seconds from the Gregorian calendar era using a [`Decimal`],
941/// when combined with the month-day-time 12-31T00:00:00, and an optional timezone offset in minutes.
942#[derive(Eq, PartialEq, PartialOrd, Debug, Clone, Copy, Hash)]
943pub struct GYear {
944    timestamp: Timestamp,
945}
946
947impl GYear {
948    pub const MAX: Self = Self {
949        timestamp: Timestamp {
950            value: Decimal::new_from_i128_unchecked(170_141_183_460_461_440_800),
951            timezone_offset: Some(TimezoneOffset::MAX),
952        },
953    };
954    pub const MIN: Self = Self {
955        timestamp: Timestamp {
956            value: Decimal::new_from_i128_unchecked(-170_141_183_460_461_700_000),
957            timezone_offset: Some(TimezoneOffset::MIN),
958        },
959    };
960
961    #[inline]
962    fn new(
963        year: i64,
964        timezone_offset: Option<TimezoneOffset>,
965    ) -> Result<Self, DateTimeOverflowError> {
966        Ok(Self {
967            timestamp: Timestamp::new(&DateTimeSevenPropertyModel {
968                year: Some(year),
969                month: None,
970                day: None,
971                hour: None,
972                minute: None,
973                second: None,
974                timezone_offset,
975            })?,
976        })
977    }
978
979    #[inline]
980    #[must_use]
981    pub fn from_be_bytes(bytes: [u8; 18]) -> Self {
982        Self {
983            timestamp: Timestamp::from_be_bytes(bytes),
984        }
985    }
986
987    #[inline]
988    #[must_use]
989    pub fn year(self) -> i64 {
990        self.timestamp.year()
991    }
992
993    #[inline]
994    #[must_use]
995    pub fn timezone(self) -> Option<DayTimeDuration> {
996        Some(self.timezone_offset()?.into())
997    }
998
999    #[inline]
1000    #[must_use]
1001    pub fn timezone_offset(self) -> Option<TimezoneOffset> {
1002        self.timestamp.timezone_offset()
1003    }
1004
1005    #[inline]
1006    #[must_use]
1007    pub fn adjust(self, timezone_offset: Option<TimezoneOffset>) -> Option<Self> {
1008        Some(Self {
1009            timestamp: self.timestamp.adjust(timezone_offset)?,
1010        })
1011    }
1012
1013    #[inline]
1014    #[must_use]
1015    pub fn to_be_bytes(self) -> [u8; 18] {
1016        self.timestamp.to_be_bytes()
1017    }
1018
1019    /// Checks if the two values are [identical](https://www.w3.org/TR/xmlschema11-2/#identity).
1020    #[inline]
1021    #[must_use]
1022    pub fn is_identical_with(self, other: Self) -> bool {
1023        self.timestamp.is_identical_with(other.timestamp)
1024    }
1025}
1026
1027/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
1028impl TryFrom<DateTime> for GYear {
1029    type Error = DateTimeOverflowError;
1030
1031    #[inline]
1032    fn try_from(date_time: DateTime) -> Result<Self, Self::Error> {
1033        Self::new(date_time.year(), date_time.timezone_offset())
1034    }
1035}
1036
1037/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
1038impl TryFrom<Date> for GYear {
1039    type Error = DateTimeOverflowError;
1040
1041    #[inline]
1042    fn try_from(date: Date) -> Result<Self, Self::Error> {
1043        Self::new(date.year(), date.timezone_offset())
1044    }
1045}
1046
1047impl TryFrom<GYearMonth> for GYear {
1048    type Error = DateTimeOverflowError;
1049
1050    #[inline]
1051    fn try_from(year_month: GYearMonth) -> Result<Self, Self::Error> {
1052        Self::new(year_month.year(), year_month.timezone_offset())
1053    }
1054}
1055
1056impl FromStr for GYear {
1057    type Err = ParseDateTimeError;
1058
1059    fn from_str(input: &str) -> Result<Self, Self::Err> {
1060        ensure_complete(input, g_year_lexical_rep)
1061    }
1062}
1063
1064impl fmt::Display for GYear {
1065    #[inline]
1066    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1067        let year = self.year();
1068        if year < 0 {
1069            f.write_str("-")?;
1070        }
1071        write!(f, "{:04}", year.abs())?;
1072        if let Some(timezone_offset) = self.timezone_offset() {
1073            write!(f, "{timezone_offset}")?;
1074        }
1075        Ok(())
1076    }
1077}
1078
1079/// [XML Schema `gMonthDay` datatype](https://www.w3.org/TR/xmlschema11-2/#gMonthDay)
1080///
1081/// It encodes the value using a number of seconds from the Gregorian calendar era using a [`Decimal`],
1082/// when combined with the year 1972 and the time 31T00:00:00, and an optional timezone offset in minutes.
1083#[derive(Eq, PartialEq, PartialOrd, Debug, Clone, Copy, Hash)]
1084pub struct GMonthDay {
1085    timestamp: Timestamp,
1086}
1087
1088impl GMonthDay {
1089    #[inline]
1090    fn new(
1091        month: u8,
1092        day: u8,
1093        timezone_offset: Option<TimezoneOffset>,
1094    ) -> Result<Self, DateTimeOverflowError> {
1095        Ok(Self {
1096            timestamp: Timestamp::new(&DateTimeSevenPropertyModel {
1097                year: None,
1098                month: Some(month),
1099                day: Some(day),
1100                hour: None,
1101                minute: None,
1102                second: None,
1103                timezone_offset,
1104            })?,
1105        })
1106    }
1107
1108    #[inline]
1109    #[must_use]
1110    pub fn from_be_bytes(bytes: [u8; 18]) -> Self {
1111        Self {
1112            timestamp: Timestamp::from_be_bytes(bytes),
1113        }
1114    }
1115
1116    #[inline]
1117    #[must_use]
1118    pub fn month(&self) -> u8 {
1119        self.timestamp.month()
1120    }
1121
1122    #[inline]
1123    #[must_use]
1124    pub fn day(&self) -> u8 {
1125        self.timestamp.day()
1126    }
1127
1128    #[inline]
1129    #[must_use]
1130    pub fn timezone(&self) -> Option<DayTimeDuration> {
1131        Some(self.timezone_offset()?.into())
1132    }
1133
1134    #[inline]
1135    #[must_use]
1136    pub fn timezone_offset(&self) -> Option<TimezoneOffset> {
1137        self.timestamp.timezone_offset()
1138    }
1139
1140    #[inline]
1141    #[must_use]
1142    pub fn adjust(&self, timezone_offset: Option<TimezoneOffset>) -> Option<Self> {
1143        Some(Self {
1144            timestamp: self.timestamp.adjust(timezone_offset)?,
1145        })
1146    }
1147
1148    #[inline]
1149    #[must_use]
1150    pub fn to_be_bytes(self) -> [u8; 18] {
1151        self.timestamp.to_be_bytes()
1152    }
1153
1154    /// Checks if the two values are [identical](https://www.w3.org/TR/xmlschema11-2/#identity).
1155    #[inline]
1156    #[must_use]
1157    pub fn is_identical_with(self, other: Self) -> bool {
1158        self.timestamp.is_identical_with(other.timestamp)
1159    }
1160}
1161
1162/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
1163impl From<DateTime> for GMonthDay {
1164    #[inline]
1165    fn from(date_time: DateTime) -> Self {
1166        Self::new(
1167            date_time.month(),
1168            date_time.day(),
1169            date_time.timezone_offset(),
1170        )
1171        .expect("Casting from xsd:dateTime to xsd:gMonthDay can't fail")
1172    }
1173}
1174
1175/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
1176impl From<Date> for GMonthDay {
1177    #[inline]
1178    fn from(date: Date) -> Self {
1179        Self::new(date.month(), date.day(), date.timezone_offset())
1180            .expect("Casting from xsd:date to xsd:gMonthDay can't fail")
1181    }
1182}
1183
1184impl FromStr for GMonthDay {
1185    type Err = ParseDateTimeError;
1186
1187    fn from_str(input: &str) -> Result<Self, Self::Err> {
1188        ensure_complete(input, g_month_day_lexical_rep)
1189    }
1190}
1191
1192impl fmt::Display for GMonthDay {
1193    #[inline]
1194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1195        write!(f, "--{:02}-{:02}", self.month(), self.day())?;
1196        if let Some(timezone_offset) = self.timezone_offset() {
1197            write!(f, "{timezone_offset}")?;
1198        }
1199        Ok(())
1200    }
1201}
1202
1203/// [XML Schema `gMonth` datatype](https://www.w3.org/TR/xmlschema11-2/#gMonth)
1204///
1205/// It encodes the value using a number of seconds from the Gregorian calendar era using a [`Decimal`],
1206/// when combined with the year 1972 and the day-time 31T00:00:00, and an optional timezone offset in minutes.
1207#[derive(Eq, PartialEq, PartialOrd, Debug, Clone, Copy, Hash)]
1208pub struct GMonth {
1209    timestamp: Timestamp,
1210}
1211
1212impl GMonth {
1213    #[inline]
1214    fn new(
1215        month: u8,
1216        timezone_offset: Option<TimezoneOffset>,
1217    ) -> Result<Self, DateTimeOverflowError> {
1218        Ok(Self {
1219            timestamp: Timestamp::new(&DateTimeSevenPropertyModel {
1220                year: None,
1221                month: Some(month),
1222                day: None,
1223                hour: None,
1224                minute: None,
1225                second: None,
1226                timezone_offset,
1227            })?,
1228        })
1229    }
1230
1231    #[inline]
1232    #[must_use]
1233    pub fn from_be_bytes(bytes: [u8; 18]) -> Self {
1234        Self {
1235            timestamp: Timestamp::from_be_bytes(bytes),
1236        }
1237    }
1238
1239    #[inline]
1240    #[must_use]
1241    pub fn month(&self) -> u8 {
1242        self.timestamp.month()
1243    }
1244
1245    #[inline]
1246    #[must_use]
1247    pub fn timezone(&self) -> Option<DayTimeDuration> {
1248        Some(self.timezone_offset()?.into())
1249    }
1250
1251    #[inline]
1252    #[must_use]
1253    pub fn timezone_offset(&self) -> Option<TimezoneOffset> {
1254        self.timestamp.timezone_offset()
1255    }
1256
1257    #[inline]
1258    #[must_use]
1259    pub fn adjust(&self, timezone_offset: Option<TimezoneOffset>) -> Option<Self> {
1260        Some(Self {
1261            timestamp: self.timestamp.adjust(timezone_offset)?,
1262        })
1263    }
1264
1265    #[inline]
1266    #[must_use]
1267    pub fn to_be_bytes(self) -> [u8; 18] {
1268        self.timestamp.to_be_bytes()
1269    }
1270
1271    /// Checks if the two values are [identical](https://www.w3.org/TR/xmlschema11-2/#identity).
1272    #[inline]
1273    #[must_use]
1274    pub fn is_identical_with(self, other: Self) -> bool {
1275        self.timestamp.is_identical_with(other.timestamp)
1276    }
1277}
1278
1279/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
1280impl From<DateTime> for GMonth {
1281    #[inline]
1282    fn from(date_time: DateTime) -> Self {
1283        Self::new(date_time.month(), date_time.timezone_offset())
1284            .expect("Casting from xsd:dateTime to xsd:gMonth can't fail")
1285    }
1286}
1287
1288/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
1289impl From<Date> for GMonth {
1290    #[inline]
1291    fn from(date: Date) -> Self {
1292        Self::new(date.month(), date.timezone_offset())
1293            .expect("Casting from xsd:date to xsd:gMonth can't fail")
1294    }
1295}
1296
1297impl From<GYearMonth> for GMonth {
1298    #[inline]
1299    fn from(year_month: GYearMonth) -> Self {
1300        Self::new(year_month.month(), year_month.timezone_offset())
1301            .expect("Casting from xsd:gYearMonth to xsd:gMonth can't fail")
1302    }
1303}
1304
1305impl From<GMonthDay> for GMonth {
1306    #[inline]
1307    fn from(month_day: GMonthDay) -> Self {
1308        Self::new(month_day.month(), month_day.timezone_offset())
1309            .expect("Casting from xsd:gMonthDay to xsd:gMonth can't fail")
1310    }
1311}
1312
1313impl FromStr for GMonth {
1314    type Err = ParseDateTimeError;
1315
1316    fn from_str(input: &str) -> Result<Self, Self::Err> {
1317        ensure_complete(input, g_month_lexical_rep)
1318    }
1319}
1320
1321impl fmt::Display for GMonth {
1322    #[inline]
1323    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324        write!(f, "--{:02}", self.month())?;
1325        if let Some(timezone_offset) = self.timezone_offset() {
1326            write!(f, "{timezone_offset}")?;
1327        }
1328        Ok(())
1329    }
1330}
1331
1332/// [XML Schema `date` datatype](https://www.w3.org/TR/xmlschema11-2/#date)
1333///
1334/// It encodes the value using a number of seconds from the Gregorian calendar era using a [`Decimal`],
1335/// when combined with the year-month 1972-12 and the 00:00:00, and an optional timezone offset in minutes.
1336#[derive(Eq, PartialEq, PartialOrd, Debug, Clone, Copy, Hash)]
1337pub struct GDay {
1338    timestamp: Timestamp,
1339}
1340
1341impl GDay {
1342    #[inline]
1343    fn new(
1344        day: u8,
1345        timezone_offset: Option<TimezoneOffset>,
1346    ) -> Result<Self, DateTimeOverflowError> {
1347        Ok(Self {
1348            timestamp: Timestamp::new(&DateTimeSevenPropertyModel {
1349                year: None,
1350                month: None,
1351                day: Some(day),
1352                hour: None,
1353                minute: None,
1354                second: None,
1355                timezone_offset,
1356            })?,
1357        })
1358    }
1359
1360    #[inline]
1361    #[must_use]
1362    pub fn from_be_bytes(bytes: [u8; 18]) -> Self {
1363        Self {
1364            timestamp: Timestamp::from_be_bytes(bytes),
1365        }
1366    }
1367
1368    #[inline]
1369    #[must_use]
1370    pub fn day(&self) -> u8 {
1371        self.timestamp.day()
1372    }
1373
1374    #[inline]
1375    #[must_use]
1376    pub fn timezone(&self) -> Option<DayTimeDuration> {
1377        Some(self.timezone_offset()?.into())
1378    }
1379
1380    #[inline]
1381    #[must_use]
1382    pub fn timezone_offset(&self) -> Option<TimezoneOffset> {
1383        self.timestamp.timezone_offset()
1384    }
1385
1386    #[inline]
1387    #[must_use]
1388    pub fn adjust(&self, timezone_offset: Option<TimezoneOffset>) -> Option<Self> {
1389        Some(Self {
1390            timestamp: self.timestamp.adjust(timezone_offset)?,
1391        })
1392    }
1393
1394    #[inline]
1395    #[must_use]
1396    pub fn to_be_bytes(self) -> [u8; 18] {
1397        self.timestamp.to_be_bytes()
1398    }
1399
1400    /// Checks if the two values are [identical](https://www.w3.org/TR/xmlschema11-2/#identity).
1401    #[inline]
1402    #[must_use]
1403    pub fn is_identical_with(self, other: Self) -> bool {
1404        self.timestamp.is_identical_with(other.timestamp)
1405    }
1406}
1407
1408/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
1409impl From<DateTime> for GDay {
1410    #[inline]
1411    fn from(date_time: DateTime) -> Self {
1412        Self::new(date_time.day(), date_time.timezone_offset())
1413            .expect("Casting from xsd:dateTime to xsd:gDay can't fail")
1414    }
1415}
1416
1417/// Conversion according to [XPath cast rules](https://www.w3.org/TR/xpath-functions-31/#casting-to-datetimes).
1418impl From<Date> for GDay {
1419    #[inline]
1420    fn from(date: Date) -> Self {
1421        Self::new(date.day(), date.timezone_offset())
1422            .expect("Casting from xsd:date to xsd:gDay can't fail")
1423    }
1424}
1425
1426impl From<GMonthDay> for GDay {
1427    #[inline]
1428    fn from(month_day: GMonthDay) -> Self {
1429        Self::new(month_day.day(), month_day.timezone_offset())
1430            .expect("Casting from xsd:gMonthDay to xsd:gDay can't fail")
1431    }
1432}
1433
1434impl FromStr for GDay {
1435    type Err = ParseDateTimeError;
1436
1437    fn from_str(input: &str) -> Result<Self, Self::Err> {
1438        ensure_complete(input, g_day_lexical_rep)
1439    }
1440}
1441
1442impl fmt::Display for GDay {
1443    #[inline]
1444    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1445        write!(f, "---{:02}", self.day())?;
1446        if let Some(timezone_offset) = self.timezone_offset() {
1447            write!(f, "{timezone_offset}")?;
1448        }
1449        Ok(())
1450    }
1451}
1452
1453/// A timezone offset with respect to UTC.
1454///
1455/// It is encoded as a number of minutes between -PT14H and PT14H.
1456#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Copy, Hash, Serialize, Deserialize)]
1457pub struct TimezoneOffset {
1458    offset: i16, // in minute with respect to UTC
1459}
1460
1461impl TimezoneOffset {
1462    pub const MAX: Self = Self { offset: 14 * 60 };
1463    pub const MIN: Self = Self { offset: -14 * 60 };
1464    pub const UTC: Self = Self { offset: 0 };
1465
1466    /// From offset in minute with respect to UTC
1467    #[inline]
1468    pub fn new(offset_in_minutes: i16) -> Result<Self, InvalidTimezoneError> {
1469        let value = Self {
1470            offset: offset_in_minutes,
1471        };
1472        if Self::MIN <= value && value <= Self::MAX {
1473            Ok(value)
1474        } else {
1475            Err(InvalidTimezoneError {
1476                offset_in_minutes: offset_in_minutes.into(),
1477            })
1478        }
1479    }
1480
1481    #[inline]
1482    #[must_use]
1483    pub fn from_be_bytes(bytes: [u8; 2]) -> Self {
1484        Self {
1485            offset: i16::from_be_bytes(bytes),
1486        }
1487    }
1488
1489    #[inline]
1490    #[must_use]
1491    pub fn to_be_bytes(self) -> [u8; 2] {
1492        self.offset.to_be_bytes()
1493    }
1494}
1495
1496impl TryFrom<DayTimeDuration> for TimezoneOffset {
1497    type Error = InvalidTimezoneError;
1498
1499    #[inline]
1500    fn try_from(value: DayTimeDuration) -> Result<Self, Self::Error> {
1501        let offset_in_minutes = value.minutes() + value.hours() * 60;
1502        let result = Self::new(
1503            offset_in_minutes
1504                .try_into()
1505                .map_err(|_| Self::Error { offset_in_minutes })?,
1506        )?;
1507        if DayTimeDuration::from(result) == value {
1508            Ok(result)
1509        } else {
1510            // The value is not an integral number of minutes or overflow problems
1511            Err(Self::Error { offset_in_minutes })
1512        }
1513    }
1514}
1515
1516impl TryFrom<Duration> for TimezoneOffset {
1517    type Error = InvalidTimezoneError;
1518
1519    #[inline]
1520    fn try_from(value: Duration) -> Result<Self, Self::Error> {
1521        DayTimeDuration::try_from(value)
1522            .map_err(|_| Self::Error {
1523                offset_in_minutes: 0,
1524            })?
1525            .try_into()
1526    }
1527}
1528
1529impl From<TimezoneOffset> for DayTimeDuration {
1530    #[inline]
1531    fn from(value: TimezoneOffset) -> Self {
1532        Self::new(i64::from(value.offset) * 60)
1533    }
1534}
1535
1536impl From<TimezoneOffset> for Duration {
1537    #[inline]
1538    fn from(value: TimezoneOffset) -> Self {
1539        DayTimeDuration::from(value).into()
1540    }
1541}
1542
1543impl fmt::Display for TimezoneOffset {
1544    #[inline]
1545    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1546        match self.offset {
1547            0 => f.write_str("Z"),
1548            offset if offset < 0 => write!(f, "-{:02}:{:02}", -offset / 60, -offset % 60),
1549            offset => write!(f, "+{:02}:{:02}", offset / 60, offset % 60),
1550        }
1551    }
1552}
1553
1554/// [The Date/time Seven-property model](https://www.w3.org/TR/xmlschema11-2/#dt-dt-7PropMod)
1555#[derive(Eq, PartialEq, Debug, Clone, Hash)]
1556struct DateTimeSevenPropertyModel {
1557    year: Option<i64>,
1558    month: Option<u8>,
1559    day: Option<u8>,
1560    hour: Option<u8>,
1561    minute: Option<u8>,
1562    second: Option<Decimal>,
1563    timezone_offset: Option<TimezoneOffset>,
1564}
1565
1566#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
1567struct Timestamp {
1568    value: Decimal,
1569    timezone_offset: Option<TimezoneOffset>,
1570}
1571
1572impl PartialEq for Timestamp {
1573    #[inline]
1574    fn eq(&self, other: &Self) -> bool {
1575        match (self.timezone_offset, other.timezone_offset) {
1576            (Some(_), Some(_)) | (None, None) => self.value.eq(&other.value),
1577            _ => false, // TODO: implicit timezone
1578        }
1579    }
1580}
1581
1582impl Eq for Timestamp {}
1583
1584impl PartialOrd for Timestamp {
1585    #[inline]
1586    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1587        match (self.timezone_offset, other.timezone_offset) {
1588            (Some(_), Some(_)) | (None, None) => self.value.partial_cmp(&other.value),
1589            (Some(_), None) => {
1590                let plus_result = self
1591                    .value
1592                    .partial_cmp(&(other.value.checked_add(14 * 3600)?));
1593                let minus_result = self
1594                    .value
1595                    .partial_cmp(&(other.value.checked_sub(14 * 3600)?));
1596                if plus_result == minus_result {
1597                    plus_result
1598                } else {
1599                    None
1600                }
1601            }
1602            (None, Some(_)) => {
1603                let plus_result = self.value.checked_add(14 * 3600)?.partial_cmp(&other.value);
1604                let minus_result = self.value.checked_sub(14 * 3600)?.partial_cmp(&other.value);
1605                if plus_result == minus_result {
1606                    plus_result
1607                } else {
1608                    None
1609                }
1610            }
1611        }
1612    }
1613}
1614
1615impl Hash for Timestamp {
1616    #[inline]
1617    fn hash<H: Hasher>(&self, state: &mut H) {
1618        self.value.hash(state)
1619    }
1620}
1621
1622impl Timestamp {
1623    pub const MAX: Self = Self {
1624        value: Decimal::MAX,
1625        timezone_offset: Some(TimezoneOffset::MAX),
1626    };
1627    pub const MIN: Self = Self {
1628        value: Decimal::MIN,
1629        timezone_offset: Some(TimezoneOffset::MIN),
1630    };
1631
1632    #[inline]
1633    fn new(props: &DateTimeSevenPropertyModel) -> Result<Self, DateTimeOverflowError> {
1634        Ok(Self {
1635            timezone_offset: props.timezone_offset,
1636            value: time_on_timeline(props).ok_or(DateTimeOverflowError)?,
1637        })
1638    }
1639
1640    #[inline]
1641    fn now() -> Self {
1642        Self::new(
1643            &date_time_plus_duration(
1644                since_unix_epoch(),
1645                &DateTimeSevenPropertyModel {
1646                    year: Some(1970),
1647                    month: Some(1),
1648                    day: Some(1),
1649                    hour: Some(0),
1650                    minute: Some(0),
1651                    second: Some(Decimal::default()),
1652                    timezone_offset: Some(TimezoneOffset::UTC),
1653                },
1654            )
1655            .expect("The current time seems way in the future, it's strange"),
1656        )
1657        .expect("The current time seems way in the future, it's strange")
1658    }
1659
1660    #[inline]
1661    fn from_be_bytes(bytes: [u8; 18]) -> Self {
1662        Self {
1663            value: Decimal::from_be_bytes(bytes[0..16].try_into().unwrap()),
1664            timezone_offset: if bytes[16..18] == [u8::MAX; 2] {
1665                None
1666            } else {
1667                Some(TimezoneOffset::from_be_bytes(
1668                    bytes[16..18].try_into().unwrap(),
1669                ))
1670            },
1671        }
1672    }
1673
1674    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1675    #[inline]
1676    #[must_use]
1677    fn year_month_day(&self) -> (i64, u8, u8) {
1678        let mut days = (self.value.as_i128()
1679            + i128::from(self.timezone_offset.unwrap_or(TimezoneOffset::UTC).offset) * 60)
1680            .div_euclid(86400)
1681            + 366;
1682
1683        // Make days positive
1684        let shift = if days < 0 {
1685            let shift = days / 146_097 - 1;
1686            days -= shift * 146_097;
1687            shift * 400
1688        } else {
1689            0
1690        };
1691
1692        let year_mul_400 = days / 146_097;
1693        days -= year_mul_400 * 146_097;
1694
1695        days -= 1;
1696        let year_mul_100 = days / 36524;
1697        days -= year_mul_100 * 36524;
1698
1699        days += 1;
1700        let year_mul_4 = days / 1461;
1701        days -= year_mul_4 * 1461;
1702
1703        days -= 1;
1704        let year_mod_4 = days / 365;
1705        days -= year_mod_4 * 365;
1706
1707        let year =
1708            (400 * year_mul_400 + 100 * year_mul_100 + 4 * year_mul_4 + year_mod_4 + shift) as i64;
1709
1710        let is_leap_year = (year_mul_100 == 0 || year_mul_4 != 0) && year_mod_4 == 0;
1711        days += i128::from(is_leap_year);
1712
1713        let mut month = 0;
1714        for month_i in 1..=12 {
1715            let days_in_month = i128::from(days_in_month(Some(year), month_i));
1716            if days_in_month > days {
1717                month = month_i;
1718                break;
1719            }
1720            days -= days_in_month
1721        }
1722        let day = days as u8 + 1;
1723
1724        (year, month, day)
1725    }
1726
1727    #[inline]
1728    #[must_use]
1729    fn year(&self) -> i64 {
1730        let (year, _, _) = self.year_month_day();
1731        year
1732    }
1733
1734    #[inline]
1735    #[must_use]
1736    fn month(&self) -> u8 {
1737        let (_, month, _) = self.year_month_day();
1738        month
1739    }
1740
1741    #[inline]
1742    #[must_use]
1743    fn day(&self) -> u8 {
1744        let (_, _, day) = self.year_month_day();
1745        day
1746    }
1747
1748    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1749    #[inline]
1750    #[must_use]
1751    fn hour(&self) -> u8 {
1752        (((self.value.as_i128()
1753            + i128::from(self.timezone_offset.unwrap_or(TimezoneOffset::UTC).offset) * 60)
1754            .rem_euclid(86400))
1755            / 3600) as u8
1756    }
1757
1758    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1759    #[inline]
1760    #[must_use]
1761    fn minute(&self) -> u8 {
1762        (((self.value.as_i128()
1763            + i128::from(self.timezone_offset.unwrap_or(TimezoneOffset::UTC).offset) * 60)
1764            .rem_euclid(3600))
1765            / 60) as u8
1766    }
1767
1768    #[inline]
1769    #[must_use]
1770    fn second(&self) -> Decimal {
1771        self.value
1772            .checked_rem_euclid(60)
1773            .unwrap()
1774            .checked_abs()
1775            .unwrap()
1776    }
1777
1778    #[inline]
1779    #[must_use]
1780    const fn timezone_offset(&self) -> Option<TimezoneOffset> {
1781        self.timezone_offset
1782    }
1783
1784    #[inline]
1785    #[must_use]
1786    fn checked_add_seconds(&self, seconds: impl Into<Decimal>) -> Option<Self> {
1787        Some(Self {
1788            value: self.value.checked_add(seconds.into())?,
1789            timezone_offset: self.timezone_offset,
1790        })
1791    }
1792
1793    #[inline]
1794    #[must_use]
1795    fn checked_sub(&self, rhs: Self) -> Option<DayTimeDuration> {
1796        match (self.timezone_offset, rhs.timezone_offset) {
1797            (Some(_), Some(_)) | (None, None) => {
1798                Some(DayTimeDuration::new(self.value.checked_sub(rhs.value)?))
1799            }
1800            _ => None, // TODO: implicit timezone
1801        }
1802    }
1803
1804    #[inline]
1805    #[must_use]
1806    fn checked_sub_seconds(&self, seconds: Decimal) -> Option<Self> {
1807        Some(Self {
1808            value: self.value.checked_sub(seconds)?,
1809            timezone_offset: self.timezone_offset,
1810        })
1811    }
1812
1813    #[inline]
1814    #[must_use]
1815    fn adjust(&self, timezone_offset: Option<TimezoneOffset>) -> Option<Self> {
1816        Some(if let Some(from_timezone) = self.timezone_offset {
1817            if let Some(to_timezone) = timezone_offset {
1818                Self {
1819                    value: self.value, // We keep the timestamp
1820                    timezone_offset: Some(to_timezone),
1821                }
1822            } else {
1823                Self {
1824                    value: self
1825                        .value
1826                        .checked_add(i64::from(from_timezone.offset) * 60)?, /* We keep the literal value */
1827                    timezone_offset: None,
1828                }
1829            }
1830        } else if let Some(to_timezone) = timezone_offset {
1831            Self {
1832                value: self.value.checked_sub(i64::from(to_timezone.offset) * 60)?, /* We keep the literal value */
1833                timezone_offset: Some(to_timezone),
1834            }
1835        } else {
1836            Self {
1837                value: self.value,
1838                timezone_offset: None,
1839            }
1840        })
1841    }
1842
1843    #[inline]
1844    #[must_use]
1845    fn to_be_bytes(self) -> [u8; 18] {
1846        let mut bytes = [0; 18];
1847        bytes[0..16].copy_from_slice(&self.value.to_be_bytes());
1848        bytes[16..18].copy_from_slice(&match &self.timezone_offset {
1849            Some(timezone_offset) => timezone_offset.to_be_bytes(),
1850            None => [u8::MAX; 2],
1851        });
1852        bytes
1853    }
1854
1855    /// Checks if the two values are [identical](https://www.w3.org/TR/xmlschema11-2/#identity).
1856    #[inline]
1857    #[must_use]
1858    pub fn is_identical_with(self, other: Self) -> bool {
1859        self.value == other.value && self.timezone_offset == other.timezone_offset
1860    }
1861}
1862
1863#[cfg(feature = "custom-now")]
1864#[allow(unsafe_code)]
1865pub fn since_unix_epoch() -> Duration {
1866    extern "Rust" {
1867        fn custom_ox_now() -> Duration;
1868    }
1869
1870    // SAFETY: Must be defined, if not compilation fails
1871    unsafe { custom_ox_now() }
1872}
1873
1874#[cfg(all(
1875    feature = "js",
1876    not(feature = "custom-now"),
1877    target_family = "wasm",
1878    target_os = "unknown"
1879))]
1880fn since_unix_epoch() -> Duration {
1881    DayTimeDuration::new(
1882        Decimal::try_from(crate::oxsdatatypes::Double::from(
1883            js_sys::Date::now() / 1000.,
1884        ))
1885        .expect("The current time seems way in the future, it's strange"),
1886    )
1887    .into()
1888}
1889
1890#[cfg(not(any(
1891    feature = "custom-now",
1892    all(feature = "js", target_family = "wasm", target_os = "unknown")
1893)))]
1894fn since_unix_epoch() -> Duration {
1895    use std::time::SystemTime;
1896
1897    SystemTime::now()
1898        .duration_since(SystemTime::UNIX_EPOCH)
1899        .expect("System time before UNIX epoch")
1900        .try_into()
1901        .expect("The current time seems way in the future, it's strange")
1902}
1903
1904/// The [normalizeMonth](https://www.w3.org/TR/xmlschema11-2/#f-dt-normMo) function
1905fn normalize_month(yr: i64, mo: i64) -> Option<(i64, u8)> {
1906    if mo >= 0 {
1907        let yr = yr.checked_add(mo.checked_sub(1)?.checked_div(12)?)?;
1908        let mo = u8::try_from(mo.checked_sub(1)?.checked_rem(12)?.abs().checked_add(1)?).ok()?;
1909        Some((yr, mo))
1910    } else {
1911        // Needed to make it work with negative durations
1912        let yr = yr.checked_add(mo.checked_sub(1)?.checked_div(12)?.checked_sub(1)?)?;
1913        let mo = u8::try_from(
1914            12_i64
1915                .checked_add(mo.checked_sub(1)?.checked_rem(12)?)?
1916                .checked_add(1)?,
1917        )
1918        .ok()?;
1919        Some((yr, mo))
1920    }
1921}
1922
1923/// The [normalizeDa](https://www.w3.org/TR/xmlschema11-2/#f-dt-normDa) function
1924fn normalize_day(yr: i64, mo: i64, mut da: i64) -> Option<(i64, u8, u8)> {
1925    let (mut yr, mut mo) = normalize_month(yr, mo)?;
1926    loop {
1927        if da <= 0 {
1928            let (yr2, mo2) = normalize_month(yr, i64::from(mo).checked_sub(1)?)?;
1929            yr = yr2;
1930            mo = mo2;
1931            da = da.checked_add(days_in_month(Some(yr), mo).into())?;
1932        } else if da > days_in_month(Some(yr), mo).into() {
1933            da = da.checked_sub(days_in_month(Some(yr), mo).into())?;
1934            let (yr2, mo2) = normalize_month(yr, i64::from(mo).checked_add(1)?)?;
1935            yr = yr2;
1936            mo = mo2;
1937        } else {
1938            return Some((yr, mo, u8::try_from(da).ok()?));
1939        };
1940    }
1941}
1942
1943/// The [normalizeMinute](https://www.w3.org/TR/xmlschema11-2/#f-dt-normMi) function
1944fn normalize_minute(yr: i64, mo: i64, da: i64, hr: i64, mi: i64) -> Option<(i64, u8, u8, u8, u8)> {
1945    let hr = hr.checked_add(mi.checked_div(60)?)?;
1946    let mi = mi.checked_rem(60)?;
1947    let da = da.checked_add(hr.checked_div(24)?)?;
1948    let hr = hr.checked_rem(24)?;
1949    let (yr, mo, da) = normalize_day(yr, mo, da)?;
1950    Some((yr, mo, da, u8::try_from(hr).ok()?, u8::try_from(mi).ok()?))
1951}
1952
1953/// The [normalizeSecond](https://www.w3.org/TR/xmlschema11-2/#f-dt-normSe) function
1954fn normalize_second(
1955    yr: i64,
1956    mo: i64,
1957    da: i64,
1958    hr: i64,
1959    mi: i64,
1960    se: Decimal,
1961) -> Option<(i64, u8, u8, u8, u8, Decimal)> {
1962    let mi = mi.checked_add(i64::try_from(se.as_i128().checked_div(60)?).ok()?)?; // TODO: good idea?
1963    let se = se.checked_rem(60)?;
1964    let (yr, mo, da, hr, mi) = normalize_minute(yr, mo, da, hr, mi)?;
1965    Some((yr, mo, da, hr, mi, se))
1966}
1967
1968/// The [daysInMonth](https://www.w3.org/TR/xmlschema11-2/#f-daysInMonth) function
1969fn days_in_month(y: Option<i64>, m: u8) -> u8 {
1970    match m {
1971        2 => {
1972            if let Some(y) = y {
1973                if y % 4 != 0 || (y % 100 == 0 && y % 400 != 0) {
1974                    28
1975                } else {
1976                    29
1977                }
1978            } else {
1979                28
1980            }
1981        }
1982        4 | 6 | 9 | 11 => 30,
1983        _ => 31,
1984    }
1985}
1986
1987/// The [dateTimePlusDuration](https://www.w3.org/TR/xmlschema11-2/#vp-dt-dateTimePlusDuration) function
1988fn date_time_plus_duration(
1989    du: Duration,
1990    dt: &DateTimeSevenPropertyModel,
1991) -> Option<DateTimeSevenPropertyModel> {
1992    let yr = dt.year.unwrap_or(1);
1993    let mo = dt.month.unwrap_or(1);
1994    let da = dt.day.unwrap_or(1);
1995    let hr = dt.hour.unwrap_or(0);
1996    let mi = dt.minute.unwrap_or(0);
1997    let se = dt.second.unwrap_or_default();
1998    let mo = i64::from(mo).checked_add(du.all_months())?;
1999    let (yr, mo) = normalize_month(yr, mo)?;
2000    let da = min(da, days_in_month(Some(yr), mo));
2001    let se = se.checked_add(du.all_seconds())?;
2002    let (yr, mo, da, hr, mi, se) =
2003        normalize_second(yr, mo.into(), da.into(), hr.into(), mi.into(), se)?;
2004
2005    Some(DateTimeSevenPropertyModel {
2006        year: dt.year.map(|_| yr),
2007        month: dt.month.map(|_| mo),
2008        day: dt.day.map(|_| da),
2009        hour: dt.hour.map(|_| hr),
2010        minute: dt.minute.map(|_| mi),
2011        second: dt.second.map(|_| se),
2012        timezone_offset: dt.timezone_offset,
2013    })
2014}
2015
2016/// The [timeOnTimeline](https://www.w3.org/TR/xmlschema11-2/#vp-dt-timeOnTimeline) function
2017fn time_on_timeline(props: &DateTimeSevenPropertyModel) -> Option<Decimal> {
2018    let yr = props.year.map_or(1971, |y| y - 1);
2019    let mo = props.month.unwrap_or(12);
2020    let da = props
2021        .day
2022        .map_or_else(|| days_in_month(Some(yr + 1), mo) - 1, |d| d - 1);
2023    let hr = props.hour.unwrap_or(0);
2024    let mi = i128::from(props.minute.unwrap_or(0))
2025        - i128::from(props.timezone_offset.unwrap_or(TimezoneOffset::UTC).offset);
2026    let se = props.second.unwrap_or_default();
2027
2028    Decimal::try_from(
2029        31_536_000 * i128::from(yr)
2030            + 86400 * i128::from(yr.div_euclid(400) - yr.div_euclid(100) + yr.div_euclid(4))
2031            + 86400
2032                * (1..mo)
2033                    .map(|m| i128::from(days_in_month(Some(yr + 1), m)))
2034                    .sum::<i128>()
2035            + 86400 * i128::from(da)
2036            + 3600 * i128::from(hr)
2037            + 60 * mi,
2038    )
2039    .ok()?
2040    .checked_add(se)
2041}
2042
2043/// A parsing error
2044#[derive(Debug, thiserror::Error)]
2045#[error(transparent)]
2046pub struct ParseDateTimeError(#[from] ParseDateTimeErrorKind);
2047
2048#[derive(Debug, Clone, thiserror::Error)]
2049enum ParseDateTimeErrorKind {
2050    #[error("{day} is not a valid day of {month}")]
2051    InvalidDayOfMonth { day: u8, month: u8 },
2052    #[error(transparent)]
2053    Overflow(#[from] DateTimeOverflowError),
2054    #[error(transparent)]
2055    InvalidTimezone(InvalidTimezoneError),
2056    #[error("{0}")]
2057    Message(&'static str),
2058}
2059
2060impl ParseDateTimeError {
2061    const fn msg(message: &'static str) -> Self {
2062        Self(ParseDateTimeErrorKind::Message(message))
2063    }
2064}
2065
2066// [16]   dateTimeLexicalRep ::= yearFrag '-' monthFrag '-' dayFrag 'T' ((hourFrag ':' minuteFrag ':' secondFrag) | endOfDayFrag) timezoneFrag?
2067fn date_time_lexical_rep(input: &str) -> Result<(DateTime, &str), ParseDateTimeError> {
2068    let (year, input) = year_frag(input)?;
2069    let input = expect_char(input, '-', "The year and month must be separated by '-'")?;
2070    let (month, input) = month_frag(input)?;
2071    let input = expect_char(input, '-', "The month and day must be separated by '-'")?;
2072    let (day, input) = day_frag(input)?;
2073    let input = expect_char(input, 'T', "The date and time must be separated by 'T'")?;
2074    let (hour, input) = hour_frag(input)?;
2075    let input = expect_char(input, ':', "The hours and minutes must be separated by ':'")?;
2076    let (minute, input) = minute_frag(input)?;
2077    let input = expect_char(
2078        input,
2079        ':',
2080        "The minutes and seconds must be separated by ':'",
2081    )?;
2082    let (second, input) = second_frag(input)?;
2083    // We validate 24:00:00
2084    if hour == 24 && minute != 0 && second != Decimal::from(0) {
2085        return Err(ParseDateTimeError::msg(
2086            "Times are not allowed to be after 24:00:00",
2087        ));
2088    }
2089    let (timezone_offset, input) = optional_end(input, timezone_frag)?;
2090    validate_day_of_month(Some(year), month, day)?;
2091    Ok((
2092        DateTime::new(year, month, day, hour, minute, second, timezone_offset)?,
2093        input,
2094    ))
2095}
2096
2097// [17]   timeLexicalRep ::= ((hourFrag ':' minuteFrag ':' secondFrag) | endOfDayFrag) timezoneFrag?
2098fn time_lexical_rep(input: &str) -> Result<(Time, &str), ParseDateTimeError> {
2099    let (hour, input) = hour_frag(input)?;
2100    let input = expect_char(input, ':', "The hours and minutes must be separated by ':'")?;
2101    let (minute, input) = minute_frag(input)?;
2102    let input = expect_char(
2103        input,
2104        ':',
2105        "The minutes and seconds must be separated by ':'",
2106    )?;
2107    let (second, input) = second_frag(input)?;
2108    // We validate 24:00:00
2109    if hour == 24 && minute != 0 && second != Decimal::from(0) {
2110        return Err(ParseDateTimeError::msg(
2111            "Times are not allowed to be after 24:00:00",
2112        ));
2113    }
2114    let (timezone_offset, input) = optional_end(input, timezone_frag)?;
2115    Ok((Time::new(hour, minute, second, timezone_offset)?, input))
2116}
2117
2118// [18]   dateLexicalRep ::= yearFrag '-' monthFrag '-' dayFrag timezoneFrag?   Constraint:  Day-of-month Representations
2119fn date_lexical_rep(input: &str) -> Result<(Date, &str), ParseDateTimeError> {
2120    let (year, input) = year_frag(input)?;
2121    let input = expect_char(input, '-', "The year and month must be separated by '-'")?;
2122    let (month, input) = month_frag(input)?;
2123    let input = expect_char(input, '-', "The month and day must be separated by '-'")?;
2124    let (day, input) = day_frag(input)?;
2125    let (timezone_offset, input) = optional_end(input, timezone_frag)?;
2126    validate_day_of_month(Some(year), month, day)?;
2127    Ok((Date::new(year, month, day, timezone_offset)?, input))
2128}
2129
2130// [19]   gYearMonthLexicalRep ::= yearFrag '-' monthFrag timezoneFrag?
2131fn g_year_month_lexical_rep(input: &str) -> Result<(GYearMonth, &str), ParseDateTimeError> {
2132    let (year, input) = year_frag(input)?;
2133    let input = expect_char(input, '-', "The year and month must be separated by '-'")?;
2134    let (month, input) = month_frag(input)?;
2135    let (timezone_offset, input) = optional_end(input, timezone_frag)?;
2136    Ok((GYearMonth::new(year, month, timezone_offset)?, input))
2137}
2138
2139// [20]   gYearLexicalRep ::= yearFrag timezoneFrag?
2140fn g_year_lexical_rep(input: &str) -> Result<(GYear, &str), ParseDateTimeError> {
2141    let (year, input) = year_frag(input)?;
2142    let (timezone_offset, input) = optional_end(input, timezone_frag)?;
2143    Ok((GYear::new(year, timezone_offset)?, input))
2144}
2145
2146// [21]   gMonthDayLexicalRep ::= '--' monthFrag '-' dayFrag timezoneFrag?   Constraint:  Day-of-month Representations
2147fn g_month_day_lexical_rep(input: &str) -> Result<(GMonthDay, &str), ParseDateTimeError> {
2148    let input = expect_char(input, '-', "gMonthDay values must start with '--'")?;
2149    let input = expect_char(input, '-', "gMonthDay values must start with '--'")?;
2150    let (month, input) = month_frag(input)?;
2151    let input = expect_char(input, '-', "The month and day must be separated by '-'")?;
2152    let (day, input) = day_frag(input)?;
2153    let (timezone_offset, input) = optional_end(input, timezone_frag)?;
2154    validate_day_of_month(None, month, day)?;
2155    Ok((GMonthDay::new(month, day, timezone_offset)?, input))
2156}
2157
2158// [22]   gDayLexicalRep ::= '---' dayFrag timezoneFrag?
2159fn g_day_lexical_rep(input: &str) -> Result<(GDay, &str), ParseDateTimeError> {
2160    let input = expect_char(input, '-', "gDay values must start with '---'")?;
2161    let input = expect_char(input, '-', "gDay values must start with '---'")?;
2162    let input = expect_char(input, '-', "gDay values must start with '---'")?;
2163    let (day, input) = day_frag(input)?;
2164    let (timezone_offset, input) = optional_end(input, timezone_frag)?;
2165    Ok((GDay::new(day, timezone_offset)?, input))
2166}
2167
2168// [23]   gMonthLexicalRep ::= '--' monthFrag timezoneFrag?
2169fn g_month_lexical_rep(input: &str) -> Result<(GMonth, &str), ParseDateTimeError> {
2170    let input = expect_char(input, '-', "gMonth values must start with '--'")?;
2171    let input = expect_char(input, '-', "gMonth values must start with '--'")?;
2172    let (month, input) = month_frag(input)?;
2173    let (timezone_offset, input) = optional_end(input, timezone_frag)?;
2174    Ok((GMonth::new(month, timezone_offset)?, input))
2175}
2176
2177// [56]   yearFrag ::= '-'? (([1-9] digit digit digit+)) | ('0' digit digit digit))
2178fn year_frag(input: &str) -> Result<(i64, &str), ParseDateTimeError> {
2179    let (sign, input) = if let Some(left) = input.strip_prefix('-') {
2180        (-1, left)
2181    } else {
2182        (1, input)
2183    };
2184    let (number_str, input) = integer_prefix(input);
2185    if number_str.len() < 4 {
2186        return Err(ParseDateTimeError::msg(
2187            "The year should be encoded on 4 digits",
2188        ));
2189    }
2190    if number_str.len() > 4 && number_str.starts_with('0') {
2191        return Err(ParseDateTimeError::msg(
2192            "The years value must not start with 0 if it can be encoded in at least 4 digits",
2193        ));
2194    }
2195    let number = i64::from_str(number_str).expect("valid integer");
2196    Ok((sign * number, input))
2197}
2198
2199// [57]   monthFrag ::= ('0' [1-9]) | ('1' [0-2])
2200fn month_frag(input: &str) -> Result<(u8, &str), ParseDateTimeError> {
2201    let (number_str, input) = integer_prefix(input);
2202    if number_str.len() != 2 {
2203        return Err(ParseDateTimeError::msg(
2204            "Month must be encoded with two digits",
2205        ));
2206    }
2207    let number = u8::from_str(number_str).expect("valid integer");
2208    if !(1..=12).contains(&number) {
2209        return Err(ParseDateTimeError::msg("Month must be between 01 and 12"));
2210    }
2211    Ok((number, input))
2212}
2213
2214// [58]   dayFrag ::= ('0' [1-9]) | ([12] digit) | ('3' [01])
2215fn day_frag(input: &str) -> Result<(u8, &str), ParseDateTimeError> {
2216    let (number_str, input) = integer_prefix(input);
2217    if number_str.len() != 2 {
2218        return Err(ParseDateTimeError::msg(
2219            "Day must be encoded with two digits",
2220        ));
2221    }
2222    let number = u8::from_str(number_str).expect("valid integer");
2223    if !(1..=31).contains(&number) {
2224        return Err(ParseDateTimeError::msg("Day must be between 01 and 31"));
2225    }
2226    Ok((number, input))
2227}
2228
2229// [59]   hourFrag ::= ([01] digit) | ('2' [0-3])
2230// We also allow 24 for ease of parsing
2231fn hour_frag(input: &str) -> Result<(u8, &str), ParseDateTimeError> {
2232    let (number_str, input) = integer_prefix(input);
2233    if number_str.len() != 2 {
2234        return Err(ParseDateTimeError::msg(
2235            "Hours must be encoded with two digits",
2236        ));
2237    }
2238    let number = u8::from_str(number_str).expect("valid integer");
2239    if !(0..=24).contains(&number) {
2240        return Err(ParseDateTimeError::msg("Hours must be between 00 and 24"));
2241    }
2242    Ok((number, input))
2243}
2244
2245// [60]   minuteFrag ::= [0-5] digit
2246fn minute_frag(input: &str) -> Result<(u8, &str), ParseDateTimeError> {
2247    let (number_str, input) = integer_prefix(input);
2248    if number_str.len() != 2 {
2249        return Err(ParseDateTimeError::msg(
2250            "Minutes must be encoded with two digits",
2251        ));
2252    }
2253    let number = u8::from_str(number_str).expect("valid integer");
2254    if !(0..=59).contains(&number) {
2255        return Err(ParseDateTimeError::msg("Minutes must be between 00 and 59"));
2256    }
2257    Ok((number, input))
2258}
2259
2260// [61]   secondFrag ::= ([0-5] digit) ('.' digit+)?
2261fn second_frag(input: &str) -> Result<(Decimal, &str), ParseDateTimeError> {
2262    let (number_str, input) = decimal_prefix(input);
2263    let (before_dot_str, _) = number_str.split_once('.').unwrap_or((number_str, ""));
2264    if before_dot_str.len() != 2 {
2265        return Err(ParseDateTimeError::msg(
2266            "Seconds must be encoded with two digits",
2267        ));
2268    }
2269    let number = Decimal::from_str(number_str)
2270        .map_err(|_| ParseDateTimeError::msg("The second precision is too large"))?;
2271    if number < Decimal::from(0) || number >= Decimal::from(60) {
2272        return Err(ParseDateTimeError::msg("Seconds must be between 00 and 60"));
2273    }
2274    if number_str.ends_with('.') {
2275        return Err(ParseDateTimeError::msg(
2276            "Seconds are not allowed to end with a dot",
2277        ));
2278    }
2279    Ok((number, input))
2280}
2281
2282// [63]   timezoneFrag ::= 'Z' | ('+' | '-') (('0' digit | '1' [0-3]) ':' minuteFrag | '14:00')
2283fn timezone_frag(input: &str) -> Result<(TimezoneOffset, &str), ParseDateTimeError> {
2284    if let Some(left) = input.strip_prefix('Z') {
2285        return Ok((TimezoneOffset::UTC, left));
2286    }
2287    let (sign, input) = if let Some(left) = input.strip_prefix('-') {
2288        (-1, left)
2289    } else if let Some(left) = input.strip_prefix('+') {
2290        (1, left)
2291    } else {
2292        (1, input)
2293    };
2294
2295    let (hour_str, input) = integer_prefix(input);
2296    if hour_str.len() != 2 {
2297        return Err(ParseDateTimeError::msg(
2298            "The timezone hours must be encoded with two digits",
2299        ));
2300    }
2301    let hours = i16::from_str(hour_str).expect("valid integer");
2302
2303    let input = expect_char(
2304        input,
2305        ':',
2306        "The timezone hours and minutes must be separated by ':'",
2307    )?;
2308    let (minutes, input) = minute_frag(input)?;
2309
2310    if hours > 13 && !(hours == 14 && minutes == 0) {
2311        return Err(ParseDateTimeError::msg(
2312            "The timezone hours must be between 00 and 13",
2313        ));
2314    }
2315
2316    Ok((
2317        TimezoneOffset::new(sign * (hours * 60 + i16::from(minutes)))
2318            .map_err(|e| ParseDateTimeError(ParseDateTimeErrorKind::InvalidTimezone(e)))?,
2319        input,
2320    ))
2321}
2322
2323fn ensure_complete<T>(
2324    input: &str,
2325    parse: impl FnOnce(&str) -> Result<(T, &str), ParseDateTimeError>,
2326) -> Result<T, ParseDateTimeError> {
2327    let (result, left) = parse(input)?;
2328    if !left.is_empty() {
2329        return Err(ParseDateTimeError::msg("Unrecognized value suffix"));
2330    }
2331    Ok(result)
2332}
2333
2334fn expect_char<'a>(
2335    input: &'a str,
2336    constant: char,
2337    error_message: &'static str,
2338) -> Result<&'a str, ParseDateTimeError> {
2339    if let Some(left) = input.strip_prefix(constant) {
2340        Ok(left)
2341    } else {
2342        Err(ParseDateTimeError::msg(error_message))
2343    }
2344}
2345
2346fn integer_prefix(input: &str) -> (&str, &str) {
2347    let mut end = input.len();
2348    for (i, c) in input.char_indices() {
2349        if !c.is_ascii_digit() {
2350            end = i;
2351            break;
2352        }
2353    }
2354    input.split_at(end)
2355}
2356
2357fn decimal_prefix(input: &str) -> (&str, &str) {
2358    let mut end = input.len();
2359    let mut dot_seen = false;
2360    for (i, c) in input.char_indices() {
2361        if c.is_ascii_digit() {
2362            // Ok
2363        } else if c == '.' && !dot_seen {
2364            dot_seen = true;
2365        } else {
2366            end = i;
2367            break;
2368        }
2369    }
2370    input.split_at(end)
2371}
2372
2373fn optional_end<T>(
2374    input: &str,
2375    parse: impl FnOnce(&str) -> Result<(T, &str), ParseDateTimeError>,
2376) -> Result<(Option<T>, &str), ParseDateTimeError> {
2377    Ok(if input.is_empty() {
2378        (None, input)
2379    } else {
2380        let (result, input) = parse(input)?;
2381        (Some(result), input)
2382    })
2383}
2384
2385fn validate_day_of_month(year: Option<i64>, month: u8, day: u8) -> Result<(), ParseDateTimeError> {
2386    // Constraint: Day-of-month Values
2387    if day > days_in_month(year, month) {
2388        return Err(ParseDateTimeError(
2389            ParseDateTimeErrorKind::InvalidDayOfMonth { day, month },
2390        ));
2391    }
2392    Ok(())
2393}
2394
2395/// An overflow during [`DateTime`]-related operations.
2396///
2397/// Matches XPath [`FODT0001` error](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0001).
2398#[derive(Debug, Clone, Copy, thiserror::Error)]
2399#[error("overflow during xsd:dateTime computation")]
2400pub struct DateTimeOverflowError;
2401
2402impl From<DateTimeOverflowError> for ParseDateTimeError {
2403    fn from(error: DateTimeOverflowError) -> Self {
2404        Self(ParseDateTimeErrorKind::Overflow(error))
2405    }
2406}
2407
2408/// The value provided as timezone is not valid.
2409///
2410/// Matches XPath [`FODT0003` error](https://www.w3.org/TR/xpath-functions-31/#ERRFODT0003).
2411#[derive(Debug, Clone, Copy, thiserror::Error)]
2412#[error("invalid timezone offset {}:{}",
2413        self.offset_in_minutes / 60,
2414        self.offset_in_minutes.abs() % 60)]
2415pub struct InvalidTimezoneError {
2416    offset_in_minutes: i64,
2417}
2418
2419#[cfg(test)]
2420#[allow(clippy::panic_in_result_fn)]
2421mod tests {
2422    use super::*;
2423    use std::error::Error;
2424
2425    #[test]
2426    fn from_str() -> Result<(), ParseDateTimeError> {
2427        assert_eq!(Time::from_str("00:00:00Z")?.to_string(), "00:00:00Z");
2428        assert_eq!(Time::from_str("00:00:00+00:00")?.to_string(), "00:00:00Z");
2429        assert_eq!(Time::from_str("00:00:00-00:00")?.to_string(), "00:00:00Z");
2430        assert_eq!(Time::from_str("00:00:00")?.to_string(), "00:00:00");
2431        assert_eq!(
2432            Time::from_str("00:00:00+02:00")?.to_string(),
2433            "00:00:00+02:00"
2434        );
2435        assert_eq!(
2436            Time::from_str("00:00:00+14:00")?.to_string(),
2437            "00:00:00+14:00"
2438        );
2439        assert_eq!(Time::from_str("24:00:00")?.to_string(), "00:00:00");
2440        assert_eq!(Time::from_str("24:00:00.00")?.to_string(), "00:00:00");
2441        assert_eq!(
2442            Time::from_str("23:59:59.9999999999")?.to_string(),
2443            "23:59:59.9999999999"
2444        );
2445
2446        assert_eq!(Date::from_str("0001-01-01Z")?.to_string(), "0001-01-01Z");
2447        assert_eq!(Date::from_str("0001-01-01")?.to_string(), "0001-01-01");
2448        assert_eq!(
2449            DateTime::from_str("0001-01-01T00:00:00Z")?.to_string(),
2450            "0001-01-01T00:00:00Z"
2451        );
2452        assert_eq!(
2453            DateTime::from_str("0001-01-01T00:00:00")?.to_string(),
2454            "0001-01-01T00:00:00"
2455        );
2456        assert_eq!(
2457            DateTime::from_str("1000000000-01-01T00:00:00")?.to_string(),
2458            "1000000000-01-01T00:00:00"
2459        );
2460        assert_eq!(
2461            DateTime::from_str("2001-12-31T23:59:59")?.to_string(),
2462            "2001-12-31T23:59:59"
2463        );
2464        assert_eq!(
2465            DateTime::from_str("2004-12-31T23:59:59")?.to_string(),
2466            "2004-12-31T23:59:59"
2467        );
2468        assert_eq!(
2469            DateTime::from_str("1900-12-31T23:59:59")?.to_string(),
2470            "1900-12-31T23:59:59"
2471        );
2472        assert_eq!(
2473            DateTime::from_str("2000-12-31T23:59:59")?.to_string(),
2474            "2000-12-31T23:59:59",
2475        );
2476        assert_eq!(
2477            DateTime::from_str("1899-12-31T23:59:59")?.to_string(),
2478            "1899-12-31T23:59:59"
2479        );
2480
2481        assert_eq!(
2482            DateTime::from_str("2001-02-28T23:59:59")?.to_string(),
2483            "2001-02-28T23:59:59"
2484        );
2485        assert_eq!(
2486            DateTime::from_str("2004-02-29T23:59:59")?.to_string(),
2487            "2004-02-29T23:59:59"
2488        );
2489        assert_eq!(
2490            DateTime::from_str("1900-02-28T23:59:59")?.to_string(),
2491            "1900-02-28T23:59:59"
2492        );
2493        assert_eq!(
2494            DateTime::from_str("2000-02-29T23:59:59")?.to_string(),
2495            "2000-02-29T23:59:59",
2496        );
2497        assert_eq!(
2498            DateTime::from_str("1899-02-28T23:59:59")?.to_string(),
2499            "1899-02-28T23:59:59"
2500        );
2501        assert_eq!(
2502            DateTime::from_str("2001-03-01T00:00:00")?.to_string(),
2503            "2001-03-01T00:00:00"
2504        );
2505        assert_eq!(
2506            DateTime::from_str("2004-03-01T00:00:00")?.to_string(),
2507            "2004-03-01T00:00:00"
2508        );
2509        assert_eq!(
2510            DateTime::from_str("1900-03-01T00:00:00")?.to_string(),
2511            "1900-03-01T00:00:00"
2512        );
2513        assert_eq!(
2514            DateTime::from_str("2000-03-01T00:00:00")?.to_string(),
2515            "2000-03-01T00:00:00",
2516        );
2517        assert_eq!(
2518            DateTime::from_str("1899-03-01T00:00:00")?.to_string(),
2519            "1899-03-01T00:00:00"
2520        );
2521        assert_eq!(
2522            DateTime::from_str("-0899-03-01T00:00:00")?.to_string(),
2523            "-0899-03-01T00:00:00"
2524        );
2525        assert_eq!(
2526            DateTime::from_str("2000-01-01T00:00:00.1234567")?.to_string(),
2527            "2000-01-01T00:00:00.1234567"
2528        );
2529        assert_eq!(
2530            DateTime::from_str("2000-01-01T00:00:12.1234567")?.to_string(),
2531            "2000-01-01T00:00:12.1234567"
2532        );
2533        assert_eq!(
2534            Time::from_str("01:02:03.1234567")?.to_string(),
2535            "01:02:03.1234567"
2536        );
2537        assert_eq!(
2538            Time::from_str("01:02:13.1234567")?.to_string(),
2539            "01:02:13.1234567"
2540        );
2541
2542        assert_eq!(
2543            DateTime::from_str("-1000000000-01-01T00:00:00")?.to_string(),
2544            "-1000000000-01-01T00:00:00"
2545        );
2546        assert_eq!(
2547            DateTime::from_str("-2001-12-31T23:59:59")?.to_string(),
2548            "-2001-12-31T23:59:59"
2549        );
2550        assert_eq!(
2551            DateTime::from_str("-2004-12-31T23:59:59")?.to_string(),
2552            "-2004-12-31T23:59:59"
2553        );
2554        assert_eq!(
2555            DateTime::from_str("-1900-12-31T23:59:59")?.to_string(),
2556            "-1900-12-31T23:59:59"
2557        );
2558        assert_eq!(
2559            DateTime::from_str("-2000-12-31T23:59:59")?.to_string(),
2560            "-2000-12-31T23:59:59"
2561        );
2562        assert_eq!(
2563            DateTime::from_str("-1899-12-31T23:59:59")?.to_string(),
2564            "-1899-12-31T23:59:59"
2565        );
2566
2567        assert_eq!(
2568            GYearMonth::from_str("-1899-12+01:00")?.to_string(),
2569            "-1899-12+01:00"
2570        );
2571        assert_eq!(GYearMonth::from_str("-1899-12")?.to_string(), "-1899-12");
2572        assert_eq!(GYear::from_str("-1899+01:00")?.to_string(), "-1899+01:00");
2573        assert_eq!(GYear::from_str("-1899")?.to_string(), "-1899");
2574        assert_eq!(
2575            GMonthDay::from_str("--01-01+01:00")?.to_string(),
2576            "--01-01+01:00"
2577        );
2578        assert_eq!(GMonthDay::from_str("--01-01")?.to_string(), "--01-01");
2579        assert_eq!(GDay::from_str("---01+01:00")?.to_string(), "---01+01:00");
2580        assert_eq!(GDay::from_str("---01")?.to_string(), "---01");
2581        assert_eq!(GMonth::from_str("--01+01:00")?.to_string(), "--01+01:00");
2582        assert_eq!(GMonth::from_str("--01")?.to_string(), "--01");
2583
2584        GYear::from_str("02020").unwrap_err();
2585        GYear::from_str("+2020").unwrap_err();
2586        GYear::from_str("33").unwrap_err();
2587
2588        assert_eq!(Time::from_str("00:00:00+14:00")?, Time::MIN);
2589        assert_eq!(Time::from_str("24:00:00-14:00")?, Time::MAX);
2590        Ok(())
2591    }
2592
2593    #[test]
2594    fn to_be_bytes() -> Result<(), ParseDateTimeError> {
2595        assert_eq!(
2596            DateTime::from_be_bytes(DateTime::MIN.to_be_bytes()),
2597            DateTime::MIN
2598        );
2599        assert_eq!(
2600            DateTime::from_be_bytes(DateTime::MAX.to_be_bytes()),
2601            DateTime::MAX
2602        );
2603        assert_eq!(
2604            DateTime::from_be_bytes(DateTime::from_str("2022-01-03T01:02:03")?.to_be_bytes()),
2605            DateTime::from_str("2022-01-03T01:02:03")?
2606        );
2607        assert_eq!(Date::from_be_bytes(Date::MIN.to_be_bytes()), Date::MIN);
2608        assert_eq!(Date::from_be_bytes(Date::MAX.to_be_bytes()), Date::MAX);
2609        assert_eq!(
2610            Date::from_be_bytes(Date::from_str("2022-01-03")?.to_be_bytes()),
2611            Date::from_str("2022-01-03")?
2612        );
2613        assert_eq!(Time::from_be_bytes(Time::MIN.to_be_bytes()), Time::MIN);
2614        assert_eq!(Time::from_be_bytes(Time::MAX.to_be_bytes()), Time::MAX);
2615        assert_eq!(
2616            Time::from_be_bytes(Time::from_str("01:02:03")?.to_be_bytes()),
2617            Time::from_str("01:02:03")?
2618        );
2619        assert_eq!(
2620            Time::from_be_bytes(Time::from_str("01:02:03")?.to_be_bytes()),
2621            Time::from_str("01:02:03")?
2622        );
2623        assert_eq!(
2624            GYearMonth::from_be_bytes(GYearMonth::MIN.to_be_bytes()),
2625            GYearMonth::MIN
2626        );
2627        assert_eq!(
2628            GYearMonth::from_be_bytes(GYearMonth::MAX.to_be_bytes()),
2629            GYearMonth::MAX
2630        );
2631        assert_eq!(GYear::from_be_bytes(GYear::MIN.to_be_bytes()), GYear::MIN);
2632        assert_eq!(GYear::from_be_bytes(GYear::MAX.to_be_bytes()), GYear::MAX);
2633        Ok(())
2634    }
2635
2636    #[test]
2637    fn equals() -> Result<(), ParseDateTimeError> {
2638        assert_eq!(
2639            DateTime::from_str("2002-04-02T12:00:00-01:00")?,
2640            DateTime::from_str("2002-04-02T17:00:00+04:00")?
2641        );
2642        assert_eq!(
2643            DateTime::from_str("2002-04-02T12:00:00-05:00")?,
2644            DateTime::from_str("2002-04-02T23:00:00+06:00")?
2645        );
2646        assert_ne!(
2647            DateTime::from_str("2002-04-02T12:00:00-05:00")?,
2648            DateTime::from_str("2002-04-02T17:00:00-05:00")?
2649        );
2650        assert_eq!(
2651            DateTime::from_str("2002-04-02T12:00:00-05:00")?,
2652            DateTime::from_str("2002-04-02T12:00:00-05:00")?
2653        );
2654        assert_eq!(
2655            DateTime::from_str("2002-04-02T23:00:00-04:00")?,
2656            DateTime::from_str("2002-04-03T02:00:00-01:00")?
2657        );
2658        assert_eq!(
2659            DateTime::from_str("1999-12-31T24:00:00-05:00")?,
2660            DateTime::from_str("2000-01-01T00:00:00-05:00")?
2661        );
2662        assert_ne!(
2663            DateTime::from_str("2005-04-04T24:00:00-05:00")?,
2664            DateTime::from_str("2005-04-04T00:00:00-05:00")?
2665        );
2666
2667        assert_ne!(
2668            Date::from_str("2004-12-25Z")?,
2669            Date::from_str("2004-12-25+07:00")?
2670        );
2671        assert_eq!(
2672            Date::from_str("2004-12-25-12:00")?,
2673            Date::from_str("2004-12-26+12:00")?
2674        );
2675
2676        assert_ne!(
2677            Time::from_str("08:00:00+09:00")?,
2678            Time::from_str("17:00:00-06:00")?
2679        );
2680        assert_eq!(
2681            Time::from_str("21:30:00+10:30")?,
2682            Time::from_str("06:00:00-05:00")?
2683        );
2684        assert_eq!(
2685            Time::from_str("24:00:00+01:00")?,
2686            Time::from_str("00:00:00+01:00")?
2687        );
2688
2689        assert_eq!(
2690            Time::from_str("05:00:00-03:00")?,
2691            Time::from_str("10:00:00+02:00")?
2692        );
2693        assert_ne!(
2694            Time::from_str("23:00:00-03:00")?,
2695            Time::from_str("02:00:00Z")?
2696        );
2697
2698        assert_ne!(
2699            GYearMonth::from_str("1986-02")?,
2700            GYearMonth::from_str("1986-03")?
2701        );
2702        assert_ne!(
2703            GYearMonth::from_str("1978-03")?,
2704            GYearMonth::from_str("1978-03Z")?
2705        );
2706
2707        assert_ne!(
2708            GYear::from_str("2005-12:00")?,
2709            GYear::from_str("2005+12:00")?
2710        );
2711        assert_ne!(GYear::from_str("1976-05:00")?, GYear::from_str("1976")?);
2712
2713        assert_eq!(
2714            GMonthDay::from_str("--12-25-14:00")?,
2715            GMonthDay::from_str("--12-26+10:00")?
2716        );
2717        assert_ne!(
2718            GMonthDay::from_str("--12-25")?,
2719            GMonthDay::from_str("--12-26Z")?
2720        );
2721
2722        assert_ne!(
2723            GMonth::from_str("--12-14:00")?,
2724            GMonth::from_str("--12+10:00")?
2725        );
2726        assert_ne!(GMonth::from_str("--12")?, GMonth::from_str("--12Z")?);
2727
2728        assert_ne!(
2729            GDay::from_str("---25-14:00")?,
2730            GDay::from_str("---25+10:00")?
2731        );
2732        assert_ne!(GDay::from_str("---12")?, GDay::from_str("---12Z")?);
2733        Ok(())
2734    }
2735
2736    #[test]
2737    #[allow(clippy::neg_cmp_op_on_partial_ord)]
2738    fn cmp() -> Result<(), ParseDateTimeError> {
2739        assert!(Date::from_str("2004-12-25Z")? < Date::from_str("2004-12-25-05:00")?);
2740        assert!(!(Date::from_str("2004-12-25-12:00")? < Date::from_str("2004-12-26+12:00")?));
2741
2742        assert!(Date::from_str("2004-12-25Z")? > Date::from_str("2004-12-25+07:00")?);
2743        assert!(!(Date::from_str("2004-12-25-12:00")? > Date::from_str("2004-12-26+12:00")?));
2744
2745        assert!(!(Time::from_str("12:00:00")? < Time::from_str("23:00:00+06:00")?));
2746        assert!(Time::from_str("11:00:00-05:00")? < Time::from_str("17:00:00Z")?);
2747        assert!(!(Time::from_str("23:59:59")? < Time::from_str("24:00:00")?));
2748
2749        assert!(!(Time::from_str("08:00:00+09:00")? > Time::from_str("17:00:00-06:00")?));
2750
2751        assert!(GMonthDay::from_str("--12-12+13:00")? < GMonthDay::from_str("--12-12+11:00")?);
2752        assert!(GDay::from_str("---15")? < GDay::from_str("---16")?);
2753        assert!(GDay::from_str("---15-13:00")? > GDay::from_str("---16+13:00")?);
2754        assert_eq!(
2755            GDay::from_str("---15-11:00")?,
2756            GDay::from_str("---16+13:00")?
2757        );
2758        assert!(GDay::from_str("---15-13:00")?
2759            .partial_cmp(&GDay::from_str("---16")?)
2760            .is_none());
2761        Ok(())
2762    }
2763
2764    #[test]
2765    fn year() -> Result<(), ParseDateTimeError> {
2766        assert_eq!(
2767            DateTime::from_str("1999-05-31T13:20:00-05:00")?.year(),
2768            1999
2769        );
2770        assert_eq!(
2771            DateTime::from_str("1999-05-31T21:30:00-05:00")?.year(),
2772            1999
2773        );
2774        assert_eq!(DateTime::from_str("1999-12-31T19:20:00")?.year(), 1999);
2775        assert_eq!(DateTime::from_str("1999-12-31T24:00:00")?.year(), 2000);
2776        assert_eq!(DateTime::from_str("-0002-06-06T00:00:00")?.year(), -2);
2777
2778        assert_eq!(Date::from_str("1999-05-31")?.year(), 1999);
2779        assert_eq!(Date::from_str("2000-01-01+05:00")?.year(), 2000);
2780        assert_eq!(Date::from_str("-0002-06-01")?.year(), -2);
2781
2782        assert_eq!(GYear::from_str("-0002")?.year(), -2);
2783        assert_eq!(GYearMonth::from_str("-0002-02")?.year(), -2);
2784        Ok(())
2785    }
2786
2787    #[test]
2788    fn month() -> Result<(), ParseDateTimeError> {
2789        assert_eq!(DateTime::from_str("1999-05-31T13:20:00-05:00")?.month(), 5);
2790        assert_eq!(DateTime::from_str("1999-12-31T19:20:00-05:00")?.month(), 12);
2791
2792        assert_eq!(Date::from_str("1999-05-31-05:00")?.month(), 5);
2793        assert_eq!(Date::from_str("2000-01-01+05:00")?.month(), 1);
2794
2795        assert_eq!(GMonth::from_str("--02")?.month(), 2);
2796        assert_eq!(GYearMonth::from_str("-0002-02")?.month(), 2);
2797        assert_eq!(GMonthDay::from_str("--02-03")?.month(), 2);
2798        Ok(())
2799    }
2800
2801    #[test]
2802    fn day() -> Result<(), ParseDateTimeError> {
2803        assert_eq!(DateTime::from_str("1999-05-31T13:20:00-05:00")?.day(), 31);
2804        assert_eq!(DateTime::from_str("1999-12-31T20:00:00-05:00")?.day(), 31);
2805
2806        assert_eq!(Date::from_str("1999-05-31-05:00")?.day(), 31);
2807        assert_eq!(Date::from_str("2000-01-01+05:00")?.day(), 1);
2808
2809        assert_eq!(GDay::from_str("---03")?.day(), 3);
2810        assert_eq!(GMonthDay::from_str("--02-03")?.day(), 3);
2811        Ok(())
2812    }
2813
2814    #[test]
2815    fn hour() -> Result<(), ParseDateTimeError> {
2816        assert_eq!(DateTime::from_str("1999-05-31T08:20:00-05:00")?.hour(), 8);
2817        assert_eq!(DateTime::from_str("1999-12-31T21:20:00-05:00")?.hour(), 21);
2818        assert_eq!(DateTime::from_str("1999-12-31T12:00:00")?.hour(), 12);
2819        assert_eq!(DateTime::from_str("1999-12-31T24:00:00")?.hour(), 0);
2820
2821        assert_eq!(Time::from_str("11:23:00-05:00")?.hour(), 11);
2822        assert_eq!(Time::from_str("21:23:00-05:00")?.hour(), 21);
2823        assert_eq!(Time::from_str("01:23:00+05:00")?.hour(), 1);
2824        assert_eq!(Time::from_str("24:00:00")?.hour(), 0);
2825        Ok(())
2826    }
2827
2828    #[test]
2829    fn minute() -> Result<(), ParseDateTimeError> {
2830        assert_eq!(
2831            DateTime::from_str("1999-05-31T13:20:00-05:00")?.minute(),
2832            20
2833        );
2834        assert_eq!(
2835            DateTime::from_str("1999-05-31T13:30:00+05:30")?.minute(),
2836            30
2837        );
2838
2839        assert_eq!(Time::from_str("13:00:00Z")?.minute(), 0);
2840        Ok(())
2841    }
2842
2843    #[test]
2844    fn second() -> Result<(), Box<dyn Error>> {
2845        assert_eq!(
2846            DateTime::from_str("1999-05-31T13:20:00-05:00")?.second(),
2847            Decimal::from(0)
2848        );
2849
2850        assert_eq!(
2851            Time::from_str("13:20:10.5")?.second(),
2852            Decimal::from_str("10.5")?
2853        );
2854        Ok(())
2855    }
2856
2857    #[test]
2858    fn timezone() -> Result<(), Box<dyn Error>> {
2859        assert_eq!(
2860            DateTime::from_str("1999-05-31T13:20:00-05:00")?.timezone(),
2861            Some(DayTimeDuration::from_str("-PT5H")?)
2862        );
2863        assert_eq!(
2864            DateTime::from_str("2000-06-12T13:20:00Z")?.timezone(),
2865            Some(DayTimeDuration::from_str("PT0S")?)
2866        );
2867        assert_eq!(DateTime::from_str("2004-08-27T00:00:00")?.timezone(), None);
2868
2869        assert_eq!(
2870            Date::from_str("1999-05-31-05:00")?.timezone(),
2871            Some(DayTimeDuration::from_str("-PT5H")?)
2872        );
2873        assert_eq!(
2874            Date::from_str("2000-06-12Z")?.timezone(),
2875            Some(DayTimeDuration::from_str("PT0S")?)
2876        );
2877
2878        assert_eq!(
2879            Time::from_str("13:20:00-05:00")?.timezone(),
2880            Some(DayTimeDuration::from_str("-PT5H")?)
2881        );
2882        assert_eq!(Time::from_str("13:20:00")?.timezone(), None);
2883        Ok(())
2884    }
2885
2886    #[test]
2887    fn sub() -> Result<(), Box<dyn Error>> {
2888        assert_eq!(
2889            DateTime::from_str("2000-10-30T06:12:00-05:00")?
2890                .checked_sub(DateTime::from_str("1999-11-28T09:00:00Z")?),
2891            Some(DayTimeDuration::from_str("P337DT2H12M")?)
2892        );
2893
2894        assert_eq!(
2895            Date::from_str("2000-10-30")?.checked_sub(Date::from_str("1999-11-28")?),
2896            Some(DayTimeDuration::from_str("P337D")?)
2897        );
2898        assert_eq!(
2899            Date::from_str("2000-10-30+05:00")?.checked_sub(Date::from_str("1999-11-28Z")?),
2900            Some(DayTimeDuration::from_str("P336DT19H")?)
2901        );
2902        assert_eq!(
2903            Date::from_str("2000-10-15-05:00")?.checked_sub(Date::from_str("2000-10-10+02:00")?),
2904            Some(DayTimeDuration::from_str("P5DT7H")?)
2905        );
2906
2907        assert_eq!(
2908            Time::from_str("11:12:00Z")?.checked_sub(Time::from_str("04:00:00-05:00")?),
2909            Some(DayTimeDuration::from_str("PT2H12M")?)
2910        );
2911        assert_eq!(
2912            Time::from_str("11:00:00-05:00")?.checked_sub(Time::from_str("21:30:00+05:30")?),
2913            Some(DayTimeDuration::from_str("PT0S")?)
2914        );
2915        assert_eq!(
2916            Time::from_str("17:00:00-06:00")?.checked_sub(Time::from_str("08:00:00+09:00")?),
2917            Some(DayTimeDuration::from_str("P1D")?)
2918        );
2919        assert_eq!(
2920            Time::from_str("24:00:00")?.checked_sub(Time::from_str("23:59:59")?),
2921            Some(DayTimeDuration::from_str("-PT23H59M59S")?)
2922        );
2923        Ok(())
2924    }
2925
2926    #[test]
2927    fn add_duration() -> Result<(), Box<dyn Error>> {
2928        assert_eq!(
2929            DateTime::from_str("2000-01-12T12:13:14Z")?
2930                .checked_add_duration(Duration::from_str("P1Y3M5DT7H10M3.3S")?),
2931            Some(DateTime::from_str("2001-04-17T19:23:17.3Z")?)
2932        );
2933        assert_eq!(
2934            Date::from_str("2000-01-01")?.checked_add_duration(Duration::from_str("-P3M")?),
2935            Some(Date::from_str("1999-10-01")?)
2936        );
2937        assert_eq!(
2938            Date::from_str("2000-01-12")?.checked_add_duration(Duration::from_str("PT33H")?),
2939            Some(Date::from_str("2000-01-13")?)
2940        );
2941        assert_eq!(
2942            Date::from_str("2000-03-30")?.checked_add_duration(Duration::from_str("P1D")?),
2943            Some(Date::from_str("2000-03-31")?)
2944        );
2945        assert_eq!(
2946            Date::from_str("2000-03-31")?.checked_add_duration(Duration::from_str("P1M")?),
2947            Some(Date::from_str("2000-04-30")?)
2948        );
2949        assert_eq!(
2950            Date::from_str("2000-03-30")?.checked_add_duration(Duration::from_str("P1M")?),
2951            Some(Date::from_str("2000-04-30")?)
2952        );
2953        assert_eq!(
2954            Date::from_str("2000-04-30")?.checked_add_duration(Duration::from_str("P1D")?),
2955            Some(Date::from_str("2000-05-01")?)
2956        );
2957
2958        assert_eq!(
2959            DateTime::from_str("2000-10-30T11:12:00")?
2960                .checked_add_duration(Duration::from_str("P1Y2M")?),
2961            Some(DateTime::from_str("2001-12-30T11:12:00")?)
2962        );
2963        assert_eq!(
2964            DateTime::from_str("2000-10-30T11:12:00")?
2965                .checked_add_duration(Duration::from_str("P3DT1H15M")?),
2966            Some(DateTime::from_str("2000-11-02T12:27:00")?)
2967        );
2968
2969        assert_eq!(
2970            Date::from_str("2000-10-30")?.checked_add_duration(Duration::from_str("P1Y2M")?),
2971            Some(Date::from_str("2001-12-30")?)
2972        );
2973        assert_eq!(
2974            Date::from_str("2004-10-30Z")?.checked_add_duration(Duration::from_str("P2DT2H30M0S")?),
2975            Some(Date::from_str("2004-11-01Z")?)
2976        );
2977
2978        assert_eq!(
2979            Time::from_str("11:12:00")?.checked_add_duration(Duration::from_str("P3DT1H15M")?),
2980            Some(Time::from_str("12:27:00")?)
2981        );
2982        assert_eq!(
2983            Time::from_str("23:12:00+03:00")?
2984                .checked_add_duration(Duration::from_str("P1DT3H15M")?),
2985            Some(Time::from_str("02:27:00+03:00")?)
2986        );
2987        Ok(())
2988    }
2989
2990    #[test]
2991    fn sub_duration() -> Result<(), Box<dyn Error>> {
2992        assert_eq!(
2993            DateTime::from_str("2000-10-30T11:12:00")?
2994                .checked_sub_duration(Duration::from_str("P1Y2M")?),
2995            Some(DateTime::from_str("1999-08-30T11:12:00")?)
2996        );
2997        assert_eq!(
2998            DateTime::from_str("2000-10-30T11:12:00")?
2999                .checked_sub_duration(Duration::from_str("P3DT1H15M")?),
3000            Some(DateTime::from_str("2000-10-27T09:57:00")?)
3001        );
3002
3003        assert_eq!(
3004            Date::from_str("2000-10-30")?.checked_sub_duration(Duration::from_str("P1Y2M")?),
3005            Some(Date::from_str("1999-08-30")?)
3006        );
3007        assert_eq!(
3008            Date::from_str("2000-02-29Z")?.checked_sub_duration(Duration::from_str("P1Y")?),
3009            Some(Date::from_str("1999-02-28Z")?)
3010        );
3011        assert_eq!(
3012            Date::from_str("2000-10-31-05:00")?.checked_sub_duration(Duration::from_str("P1Y1M")?),
3013            Some(Date::from_str("1999-09-30-05:00")?)
3014        );
3015        assert_eq!(
3016            Date::from_str("2000-10-30")?.checked_sub_duration(Duration::from_str("P3DT1H15M")?),
3017            Some(Date::from_str("2000-10-26")?)
3018        );
3019
3020        assert_eq!(
3021            Time::from_str("11:12:00")?.checked_sub_duration(Duration::from_str("P3DT1H15M")?),
3022            Some(Time::from_str("09:57:00")?)
3023        );
3024        assert_eq!(
3025            Time::from_str("08:20:00-05:00")?
3026                .checked_sub_duration(Duration::from_str("P23DT10H10M")?),
3027            Some(Time::from_str("22:10:00-05:00")?)
3028        );
3029        Ok(())
3030    }
3031
3032    #[test]
3033    fn adjust() -> Result<(), Box<dyn Error>> {
3034        assert_eq!(
3035            DateTime::from_str("2002-03-07T10:00:00-07:00")?
3036                .adjust(Some(DayTimeDuration::from_str("PT10H")?.try_into()?)),
3037            Some(DateTime::from_str("2002-03-08T03:00:00+10:00")?)
3038        );
3039        assert_eq!(
3040            DateTime::from_str("2002-03-07T00:00:00+01:00")?
3041                .adjust(Some(DayTimeDuration::from_str("-PT8H")?.try_into()?)),
3042            Some(DateTime::from_str("2002-03-06T15:00:00-08:00")?)
3043        );
3044        assert_eq!(
3045            DateTime::from_str("2002-03-07T10:00:00")?.adjust(None),
3046            Some(DateTime::from_str("2002-03-07T10:00:00")?)
3047        );
3048        assert_eq!(
3049            DateTime::from_str("2002-03-07T10:00:00-07:00")?.adjust(None),
3050            Some(DateTime::from_str("2002-03-07T10:00:00")?)
3051        );
3052
3053        assert_eq!(
3054            Date::from_str("2002-03-07")?
3055                .adjust(Some(DayTimeDuration::from_str("-PT10H")?.try_into()?)),
3056            Some(Date::from_str("2002-03-07-10:00")?)
3057        );
3058        assert_eq!(
3059            Date::from_str("2002-03-07-07:00")?
3060                .adjust(Some(DayTimeDuration::from_str("-PT10H")?.try_into()?)),
3061            Some(Date::from_str("2002-03-06-10:00")?)
3062        );
3063        assert_eq!(
3064            Date::from_str("2002-03-07")?.adjust(None),
3065            Some(Date::from_str("2002-03-07")?)
3066        );
3067        assert_eq!(
3068            Date::from_str("2002-03-07-07:00")?.adjust(None),
3069            Some(Date::from_str("2002-03-07")?)
3070        );
3071
3072        assert_eq!(
3073            Time::from_str("10:00:00")?
3074                .adjust(Some(DayTimeDuration::from_str("-PT10H")?.try_into()?)),
3075            Some(Time::from_str("10:00:00-10:00")?)
3076        );
3077        assert_eq!(
3078            Time::from_str("10:00:00-07:00")?
3079                .adjust(Some(DayTimeDuration::from_str("-PT10H")?.try_into()?)),
3080            Some(Time::from_str("07:00:00-10:00")?)
3081        );
3082        assert_eq!(
3083            Time::from_str("10:00:00")?.adjust(None),
3084            Some(Time::from_str("10:00:00")?)
3085        );
3086        assert_eq!(
3087            Time::from_str("10:00:00-07:00")?.adjust(None),
3088            Some(Time::from_str("10:00:00")?)
3089        );
3090        assert_eq!(
3091            Time::from_str("10:00:00-07:00")?
3092                .adjust(Some(DayTimeDuration::from_str("PT10H")?.try_into()?)),
3093            Some(Time::from_str("03:00:00+10:00")?)
3094        );
3095        Ok(())
3096    }
3097
3098    #[test]
3099    fn time_from_datetime() -> Result<(), ParseDateTimeError> {
3100        assert_eq!(
3101            Time::from(DateTime::MIN),
3102            Time::from_str("19:51:08.312696284115894272-14:00")?
3103        );
3104        assert_eq!(
3105            Time::from(DateTime::MAX),
3106            Time::from_str("04:08:51.687303715884105727+14:00")?
3107        );
3108        Ok(())
3109    }
3110
3111    #[test]
3112    fn date_from_datetime() -> Result<(), Box<dyn Error>> {
3113        assert_eq!(
3114            Date::try_from(
3115                DateTime::MIN
3116                    .checked_add_day_time_duration(DayTimeDuration::from_str("P1D")?)
3117                    .unwrap()
3118            )?,
3119            Date::MIN
3120        );
3121        assert_eq!(Date::try_from(DateTime::MAX)?, Date::MAX);
3122        Ok(())
3123    }
3124
3125    #[test]
3126    fn g_year_month_from_date() {
3127        assert_eq!(GYearMonth::from(Date::MIN), GYearMonth::MIN);
3128        assert_eq!(GYearMonth::from(Date::MAX), GYearMonth::MAX);
3129    }
3130
3131    #[test]
3132    fn g_year_from_g_year_month() -> Result<(), ParseDateTimeError> {
3133        assert_eq!(GYear::try_from(GYearMonth::MIN)?, GYear::MIN);
3134        assert_eq!(
3135            GYear::try_from(GYearMonth::from_str("5391559471918-12+14:00")?)?,
3136            GYear::MAX
3137        );
3138        Ok(())
3139    }
3140
3141    #[cfg(feature = "custom-now")]
3142    #[test]
3143    fn custom_now() {
3144        #[allow(unsafe_code)]
3145        #[no_mangle]
3146        fn custom_ox_now() -> Duration {
3147            Duration::default()
3148        }
3149        DateTime::now();
3150    }
3151
3152    #[cfg(not(feature = "custom-now"))]
3153    #[test]
3154    fn now() -> Result<(), ParseDateTimeError> {
3155        let now = DateTime::now();
3156        assert!(DateTime::from_str("2022-01-01T00:00:00Z")? < now);
3157        assert!(now < DateTime::from_str("2100-01-01T00:00:00Z")?);
3158        Ok(())
3159    }
3160
3161    #[test]
3162    fn minimally_conformant() -> Result<(), ParseDateTimeError> {
3163        // All minimally conforming processors must support nonnegative year values less than 10000
3164        // (i.e., those expressible with four digits) in all datatypes which
3165        // use the seven-property model defined in The Seven-property Model (§D.2.1)
3166        // and have a non-absent value for year (i.e. dateTime, dateTimeStamp, date, gYearMonth, and gYear).
3167        assert_eq!(GYear::from_str("9999")?.to_string(), "9999");
3168        assert_eq!(
3169            DateTime::from_str("9999-12-31T23:59:59Z")?.to_string(),
3170            "9999-12-31T23:59:59Z"
3171        );
3172
3173        // All minimally conforming processors must support second values to milliseconds
3174        // (i.e. those expressible with three fraction digits) in all datatypes
3175        // which use the seven-property model defined in The Seven-property Model (§D.2.1)
3176        // and have a non-absent value for second (i.e. dateTime, dateTimeStamp, and time).
3177        assert_eq!(
3178            Time::from_str("00:00:00.678Z")?.to_string(),
3179            "00:00:00.678Z"
3180        );
3181        assert_eq!(
3182            DateTime::from_str("2000-01-01T00:00:00.678Z")?.to_string(),
3183            "2000-01-01T00:00:00.678Z"
3184        );
3185        Ok(())
3186    }
3187}