Skip to main content

jiff/civil/
date.rs

1use core::time::Duration as UnsignedDuration;
2
3use jcore::{bounds::Sign, civil::Date as JDate};
4
5use crate::{
6    RoundMode, SignedDuration, Span, SpanRound, Unit, ZonedDateTime,
7    civil::{DateTime, Era, ISOWeekDate, Time, Weekday},
8    duration::{Duration, SDuration},
9    error::{Error, ErrorContext, civil::Error as E, unit::UnitConfigError},
10    fmt::{
11        self,
12        temporal::{DEFAULT_DATETIME_PARSER, DEFAULT_DATETIME_PRINTER},
13    },
14    tz::TimeZone,
15    util::{b, constant},
16};
17
18/// A representation of a civil date in the Gregorian calendar.
19///
20/// A `Date` value corresponds to a triple of year, month and day. Every `Date`
21/// value is guaranteed to be a valid Gregorian calendar date. For example,
22/// both `2023-02-29` and `2023-11-31` are invalid and cannot be represented by
23/// a `Date`.
24///
25/// # Civil dates
26///
27/// A `Date` value behaves without regard to daylight saving time or time
28/// zones in general. When doing arithmetic on dates with spans defined in
29/// units of time (such as with [`Date::checked_add`]), days are considered to
30/// always be precisely `86,400` seconds long.
31///
32/// # Parsing and printing
33///
34/// The `Date` type provides convenient trait implementations of
35/// [`std::str::FromStr`] and [`std::fmt::Display`]:
36///
37/// ```
38/// use jiff::civil::Date;
39///
40/// let date: Date = "2024-06-19".parse()?;
41/// assert_eq!(date.to_string(), "2024-06-19");
42///
43/// # Ok::<(), Box<dyn std::error::Error>>(())
44/// ```
45///
46/// A civil `Date` can also be parsed from something that _contains_ a date,
47/// but with perhaps other data (such as an offset or time zone):
48///
49/// ```
50/// use jiff::civil::Date;
51///
52/// let date: Date = "2024-06-19T15:22:45-04[America/New_York]".parse()?;
53/// assert_eq!(date.to_string(), "2024-06-19");
54///
55/// # Ok::<(), Box<dyn std::error::Error>>(())
56/// ```
57///
58/// For more information on the specific format supported, see the
59/// [`fmt::temporal`](crate::fmt::temporal) module documentation.
60///
61/// # Default value
62///
63/// For convenience, this type implements the `Default` trait. Its default
64/// value corresponds to `0000-01-01`. One can also access this value via the
65/// `Date::ZERO` constant.
66///
67/// # Comparisons
68///
69/// The `Date` type provides both `Eq` and `Ord` trait implementations to
70/// facilitate easy comparisons. When a date `d1` occurs before a date `d2`,
71/// then `d1 < d2`. For example:
72///
73/// ```
74/// use jiff::civil::date;
75///
76/// let d1 = date(2024, 3, 11);
77/// let d2 = date(2025, 1, 31);
78/// assert!(d1 < d2);
79/// ```
80///
81/// # Arithmetic
82///
83/// This type provides routines for adding and subtracting spans of time, as
84/// well as computing the span of time between two `Date` values.
85///
86/// For adding or subtracting spans of time, one can use any of the following
87/// routines:
88///
89/// * [`Date::checked_add`] or [`Date::checked_sub`] for checked arithmetic.
90/// * [`Date::saturating_add`] or [`Date::saturating_sub`] for saturating
91/// arithmetic.
92///
93/// Additionally, checked arithmetic is available via the `Add` and `Sub`
94/// trait implementations. When the result overflows, a panic occurs.
95///
96/// ```
97/// use jiff::{civil::date, ToSpan};
98///
99/// let start = date(2024, 2, 25);
100/// let one_week_later = start + 1.weeks();
101/// assert_eq!(one_week_later, date(2024, 3, 3));
102/// ```
103///
104/// One can compute the span of time between two dates using either
105/// [`Date::until`] or [`Date::since`]. It's also possible to subtract two
106/// `Date` values directly via a `Sub` trait implementation:
107///
108/// ```
109/// use jiff::{civil::date, ToSpan};
110///
111/// let date1 = date(2024, 3, 3);
112/// let date2 = date(2024, 2, 25);
113/// assert_eq!(date1 - date2, 7.days().fieldwise());
114/// ```
115///
116/// The `until` and `since` APIs are polymorphic and allow re-balancing and
117/// rounding the span returned. For example, the default largest unit is days
118/// (as exemplified above), but we can ask for bigger units:
119///
120/// ```
121/// use jiff::{civil::date, ToSpan, Unit};
122///
123/// let date1 = date(2024, 5, 3);
124/// let date2 = date(2024, 2, 25);
125/// assert_eq!(
126///     date1.since((Unit::Year, date2))?,
127///     2.months().days(7).fieldwise(),
128/// );
129///
130/// # Ok::<(), Box<dyn std::error::Error>>(())
131/// ```
132///
133/// Or even round the span returned:
134///
135/// ```
136/// use jiff::{civil::{DateDifference, date}, RoundMode, ToSpan, Unit};
137///
138/// let date1 = date(2024, 5, 15);
139/// let date2 = date(2024, 2, 25);
140/// assert_eq!(
141///     date1.since(
142///         DateDifference::new(date2)
143///             .smallest(Unit::Month)
144///             .largest(Unit::Year),
145///     )?,
146///     2.months().fieldwise(),
147/// );
148/// // `DateDifference` uses truncation as a rounding mode by default,
149/// // but you can set the rounding mode to break ties away from zero:
150/// assert_eq!(
151///     date1.since(
152///         DateDifference::new(date2)
153///             .smallest(Unit::Month)
154///             .largest(Unit::Year)
155///             .mode(RoundMode::HalfExpand),
156///     )?,
157///     // Rounds up to 8 days.
158///     3.months().fieldwise(),
159/// );
160///
161/// # Ok::<(), Box<dyn std::error::Error>>(())
162/// ```
163///
164/// # Rounding
165///
166/// Rounding dates is currently not supported. If you want this functionality,
167/// please participate in the [issue tracking its support][add-date-rounding].
168///
169/// [add-date-rounding]: https://github.com/BurntSushi/jiff/issues/1
170#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Date {
}
#[automatically_derived]impl ::core::clone::Clone for Date {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<JDate>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Date { }Copy, #[automatically_derived]impl ::core::cmp::Eq for Date {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<JDate>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for Date {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.inner, state)
    }
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Date { }
#[automatically_derived]impl ::core::cmp::PartialEq for Date {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.inner == other.inner }
}PartialEq, #[automatically_derived]impl ::core::cmp::PartialOrd for Date {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for Date {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.inner, &other.inner)
    }
}Ord)]
171#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
172pub struct Date {
173    inner: JDate,
174}
175
176impl Date {
177    /// The minimum representable Gregorian date.
178    ///
179    /// The minimum is chosen such that any [`Timestamp`](crate::Timestamp)
180    /// combined with any valid time zone offset can be infallibly converted to
181    /// this type. This means that the minimum `Timestamp` is guaranteed to be
182    /// bigger than the minimum `Date`.
183    pub const MIN: Date = Date::constant(-9999, 1, 1);
184
185    /// The maximum representable Gregorian date.
186    ///
187    /// The maximum is chosen such that any [`Timestamp`](crate::Timestamp)
188    /// combined with any valid time zone offset can be infallibly converted to
189    /// this type. This means that the maximum `Timestamp` is guaranteed to be
190    /// smaller than the maximum `Date`.
191    pub const MAX: Date = Date::constant(9999, 12, 31);
192
193    /// The first day of the zeroth year.
194    ///
195    /// This is guaranteed to be equivalent to `Date::default()`.
196    ///
197    /// # Example
198    ///
199    /// ```
200    /// use jiff::civil::Date;
201    ///
202    /// assert_eq!(Date::ZERO, Date::default());
203    /// ```
204    pub const ZERO: Date = Date::constant(0, 1, 1);
205
206    /// Creates a new `Date` value from its component year, month and day
207    /// values.
208    ///
209    /// To set the component values of a date after creating it, use
210    /// [`DateWith`] via [`Date::with`] to build a new [`Date`] from the fields
211    /// of an existing date.
212    ///
213    /// # Errors
214    ///
215    /// This returns an error when the given year-month-day does not
216    /// correspond to a valid date. Namely, all of the following must be
217    /// true:
218    ///
219    /// * The year must be in the range `-9999..=9999`.
220    /// * The month must be in the range `1..=12`.
221    /// * The day must be at least `1` and must be at most the number of days
222    /// in the corresponding month. So for example, `2024-02-29` is valid but
223    /// `2023-02-29` is not.
224    ///
225    /// # Example
226    ///
227    /// This shows an example of a valid date:
228    ///
229    /// ```
230    /// use jiff::civil::Date;
231    ///
232    /// let d = Date::new(2024, 2, 29).unwrap();
233    /// assert_eq!(d.year(), 2024);
234    /// assert_eq!(d.month(), 2);
235    /// assert_eq!(d.day(), 29);
236    /// ```
237    ///
238    /// This shows an example of an invalid date:
239    ///
240    /// ```
241    /// use jiff::civil::Date;
242    ///
243    /// assert!(Date::new(2023, 2, 29).is_err());
244    /// ```
245    #[inline]
246    pub fn new(year: i16, month: i8, day: i8) -> Result<Date, Error> {
247        JDate::new(year, month, day)
248            .map(Date::from_jcore)
249            .map_err(Error::jcore_range)
250    }
251
252    /// Like `Date::new`, but constrains the day value to the last day of
253    /// `month`.
254    ///
255    /// This still returns an error when `day < 1` or when `year` or `month`
256    /// are invalid.
257    #[inline]
258    fn new_constrain(year: i16, month: i8, day: i8) -> Result<Date, Error> {
259        JDate::new_constrain(year, month, day)
260            .map_err(Error::jcore_range)
261            .map(Date::from_jcore)
262    }
263
264    /*
265    /// Like `Date::new`, but does not checking on the values given when
266    /// `debug_assertions` aren't enabled.
267    ///
268    /// This is useful in contexts where the values are known to be valid.
269    ///
270    /// NOTE: It's important that this is not made public without careful
271    /// consideration. In particular, if it's public, it probably shouldn't
272    /// be safe to call so that callers can rely on the ranges of methods
273    /// like `Date::{year,month,day}`.
274    #[inline]
275    const fn new_unchecked(year: i16, month: i8, day: i8) -> Date {
276        debug_assert!(b::Year::checkc(year as i64).is_ok());
277        debug_assert!(b::Month::checkc(month as i64).is_ok());
278        debug_assert!(b::Day::checkc(day as i64).is_ok());
279        debug_assert!(day <= jcore::civil::days_in_month(year, month));
280        Date { year, month, day }
281    }
282    */
283
284    /// Creates a new `Date` value in a `const` context.
285    ///
286    /// # Panics
287    ///
288    /// This routine panics when [`Date::new`] would return an error. That is,
289    /// when the given year-month-day does not correspond to a valid date.
290    /// Namely, all of the following must be true:
291    ///
292    /// * The year must be in the range `-9999..=9999`.
293    /// * The month must be in the range `1..=12`.
294    /// * The day must be at least `1` and must be at most the number of days
295    /// in the corresponding month. So for example, `2024-02-29` is valid but
296    /// `2023-02-29` is not.
297    ///
298    /// # Example
299    ///
300    /// ```
301    /// use jiff::civil::Date;
302    ///
303    /// let d = Date::constant(2024, 2, 29);
304    /// assert_eq!(d.year(), 2024);
305    /// assert_eq!(d.month(), 2);
306    /// assert_eq!(d.day(), 29);
307    /// ```
308    #[inline]
309    pub const fn constant(year: i16, month: i8, day: i8) -> Date {
310        Date::from_jcore(match JDate::new(year, month, day) {
    Ok(val) => val,
    Err(_) => { ::core::panicking::panic_fmt(format_args!("invalid date")); }
}constant::unwrapr!(
311            JDate::new(year, month, day),
312            "invalid date"
313        ))
314    }
315
316    /// Construct a Gregorian date from an [ISO 8601 week date].
317    ///
318    /// The [`ISOWeekDate`] type describes itself in more detail, but in
319    /// brief, the ISO week date calendar system eschews months in favor of
320    /// weeks.
321    ///
322    /// The minimum and maximum values of an `ISOWeekDate` correspond
323    /// precisely to the minimum and maximum values of a `Date`. Therefore,
324    /// converting between them is lossless and infallible.
325    ///
326    /// This routine is equivalent to [`ISOWeekDate::date`]. It is also
327    /// available via a `From<ISOWeekDate>` trait implementation for `Date`.
328    ///
329    /// [ISO 8601 week date]: https://en.wikipedia.org/wiki/ISO_week_date
330    ///
331    /// # Example
332    ///
333    /// This shows a number of examples demonstrating the conversion from an
334    /// ISO 8601 week date to a Gregorian date.
335    ///
336    /// ```
337    /// use jiff::civil::{Date, ISOWeekDate, Weekday, date};
338    ///
339    /// let weekdate = ISOWeekDate::new(1994, 52, Weekday::Sunday).unwrap();
340    /// let d = Date::from_iso_week_date(weekdate);
341    /// assert_eq!(d, date(1995, 1, 1));
342    ///
343    /// let weekdate = ISOWeekDate::new(1997, 1, Weekday::Tuesday).unwrap();
344    /// let d = Date::from_iso_week_date(weekdate);
345    /// assert_eq!(d, date(1996, 12, 31));
346    ///
347    /// let weekdate = ISOWeekDate::new(2020, 1, Weekday::Monday).unwrap();
348    /// let d = Date::from_iso_week_date(weekdate);
349    /// assert_eq!(d, date(2019, 12, 30));
350    ///
351    /// let weekdate = ISOWeekDate::new(2024, 10, Weekday::Saturday).unwrap();
352    /// let d = Date::from_iso_week_date(weekdate);
353    /// assert_eq!(d, date(2024, 3, 9));
354    ///
355    /// let weekdate = ISOWeekDate::new(9999, 52, Weekday::Friday).unwrap();
356    /// let d = Date::from_iso_week_date(weekdate);
357    /// assert_eq!(d, date(9999, 12, 31));
358    /// ```
359    #[inline]
360    pub fn from_iso_week_date(weekdate: ISOWeekDate) -> Date {
361        Date::from_jcore(weekdate.to_jcore().to_date())
362    }
363
364    /// Create a builder for constructing a `Date` from the fields of this
365    /// date.
366    ///
367    /// See the methods on [`DateWith`] for the different ways one can set the
368    /// fields of a new `Date`.
369    ///
370    /// # Example
371    ///
372    /// The builder ensures one can chain together the individual components
373    /// of a date without it failing at an intermediate step. For example,
374    /// if you had a date of `2024-10-31` and wanted to change both the day
375    /// and the month, and each setting was validated independent of the other,
376    /// you would need to be careful to set the day first and then the month.
377    /// In some cases, you would need to set the month first and then the day!
378    ///
379    /// But with the builder, you can set values in any order:
380    ///
381    /// ```
382    /// use jiff::civil::date;
383    ///
384    /// let d1 = date(2024, 10, 31);
385    /// let d2 = d1.with().month(11).day(30).build()?;
386    /// assert_eq!(d2, date(2024, 11, 30));
387    ///
388    /// let d1 = date(2024, 4, 30);
389    /// let d2 = d1.with().day(31).month(7).build()?;
390    /// assert_eq!(d2, date(2024, 7, 31));
391    ///
392    /// # Ok::<(), Box<dyn std::error::Error>>(())
393    /// ```
394    #[inline]
395    pub fn with(self) -> DateWith {
396        DateWith::new(self)
397    }
398
399    /// Returns the year for this date.
400    ///
401    /// The value returned is guaranteed to be in the range `-9999..=9999`.
402    ///
403    /// # Example
404    ///
405    /// ```
406    /// use jiff::civil::date;
407    ///
408    /// let d1 = date(2024, 3, 9);
409    /// assert_eq!(d1.year(), 2024);
410    ///
411    /// let d2 = date(-2024, 3, 9);
412    /// assert_eq!(d2.year(), -2024);
413    ///
414    /// let d3 = date(0, 3, 9);
415    /// assert_eq!(d3.year(), 0);
416    /// ```
417    #[inline]
418    pub fn year(self) -> i16 {
419        self.inner.year()
420    }
421
422    /// Returns the year and its era.
423    ///
424    /// This crate specifically allows years to be negative or `0`, where as
425    /// years written for the Gregorian calendar are always positive and
426    /// greater than `0`. In the Gregorian calendar, the era labels `BCE` and
427    /// `CE` are used to disambiguate between years less than or equal to `0`
428    /// and years greater than `0`, respectively.
429    ///
430    /// The crate is designed this way so that years in the latest era (that
431    /// is, `CE`) are aligned with years in this crate.
432    ///
433    /// The year returned is guaranteed to be in the range `1..=10000`.
434    ///
435    /// # Example
436    ///
437    /// ```
438    /// use jiff::civil::{Era, date};
439    ///
440    /// let d = date(2024, 10, 3);
441    /// assert_eq!(d.era_year(), (2024, Era::CE));
442    ///
443    /// let d = date(1, 10, 3);
444    /// assert_eq!(d.era_year(), (1, Era::CE));
445    ///
446    /// let d = date(0, 10, 3);
447    /// assert_eq!(d.era_year(), (1, Era::BCE));
448    ///
449    /// let d = date(-1, 10, 3);
450    /// assert_eq!(d.era_year(), (2, Era::BCE));
451    ///
452    /// let d = date(-10, 10, 3);
453    /// assert_eq!(d.era_year(), (11, Era::BCE));
454    ///
455    /// let d = date(-9_999, 10, 3);
456    /// assert_eq!(d.era_year(), (10_000, Era::BCE));
457    /// ```
458    #[inline]
459    pub fn era_year(self) -> (i16, Era) {
460        let year = self.year();
461        if year >= 1 {
462            (year, Era::CE)
463        } else {
464            // We specifically ensure our min/max bounds on `Year` always leave
465            // room in its representation to add or subtract 1, so this will
466            // never fail.
467            let era_year = -year + 1;
468            (era_year, Era::BCE)
469        }
470    }
471
472    /// Returns the month for this date.
473    ///
474    /// The value returned is guaranteed to be in the range `1..=12`.
475    ///
476    /// # Example
477    ///
478    /// ```
479    /// use jiff::civil::date;
480    ///
481    /// let d1 = date(2024, 3, 9);
482    /// assert_eq!(d1.month(), 3);
483    /// ```
484    #[inline]
485    pub fn month(self) -> i8 {
486        self.inner.month()
487    }
488
489    /// Returns the day for this date.
490    ///
491    /// The value returned is guaranteed to be in the range `1..=31`.
492    ///
493    /// # Example
494    ///
495    /// ```
496    /// use jiff::civil::date;
497    ///
498    /// let d1 = date(2024, 2, 29);
499    /// assert_eq!(d1.day(), 29);
500    /// ```
501    #[inline]
502    pub fn day(self) -> i8 {
503        self.inner.day()
504    }
505
506    /// Returns the weekday corresponding to this date.
507    ///
508    /// # Example
509    ///
510    /// ```
511    /// use jiff::civil::{Weekday, date};
512    ///
513    /// // The Unix epoch was on a Thursday.
514    /// let d1 = date(1970, 1, 1);
515    /// assert_eq!(d1.weekday(), Weekday::Thursday);
516    /// // One can also get the weekday as an offset in a variety of schemes.
517    /// assert_eq!(d1.weekday().to_monday_zero_offset(), 3);
518    /// assert_eq!(d1.weekday().to_monday_one_offset(), 4);
519    /// assert_eq!(d1.weekday().to_sunday_zero_offset(), 4);
520    /// assert_eq!(d1.weekday().to_sunday_one_offset(), 5);
521    /// ```
522    #[inline]
523    pub fn weekday(self) -> Weekday {
524        Weekday::from_jcore(self.inner.weekday())
525    }
526
527    /// Returns the ordinal day of the year that this date resides in.
528    ///
529    /// For leap years, this always returns a value in the range `1..=366`.
530    /// Otherwise, the value is in the range `1..=365`.
531    ///
532    /// # Example
533    ///
534    /// ```
535    /// use jiff::civil::date;
536    ///
537    /// let d = date(2006, 8, 24);
538    /// assert_eq!(d.day_of_year(), 236);
539    ///
540    /// let d = date(2023, 12, 31);
541    /// assert_eq!(d.day_of_year(), 365);
542    ///
543    /// let d = date(2024, 12, 31);
544    /// assert_eq!(d.day_of_year(), 366);
545    /// ```
546    #[inline]
547    pub fn day_of_year(self) -> i16 {
548        self.inner.day_of_year()
549    }
550
551    /// Returns the ordinal day of the year that this date resides in, but
552    /// ignores leap years.
553    ///
554    /// That is, the range of possible values returned by this routine is
555    /// `1..=365`, even if this date resides in a leap year. If this date is
556    /// February 29, then this routine returns `None`.
557    ///
558    /// The value `365` always corresponds to the last day in the year,
559    /// December 31, even for leap years.
560    ///
561    /// # Example
562    ///
563    /// ```
564    /// use jiff::civil::date;
565    ///
566    /// let d = date(2006, 8, 24);
567    /// assert_eq!(d.day_of_year_no_leap(), Some(236));
568    ///
569    /// let d = date(2023, 12, 31);
570    /// assert_eq!(d.day_of_year_no_leap(), Some(365));
571    ///
572    /// let d = date(2024, 12, 31);
573    /// assert_eq!(d.day_of_year_no_leap(), Some(365));
574    ///
575    /// let d = date(2024, 2, 29);
576    /// assert_eq!(d.day_of_year_no_leap(), None);
577    /// ```
578    #[inline]
579    pub fn day_of_year_no_leap(self) -> Option<i16> {
580        self.inner.day_of_year_no_leap()
581    }
582
583    /// Returns the first date of the month that this date resides in.
584    ///
585    /// # Example
586    ///
587    /// ```
588    /// use jiff::civil::date;
589    ///
590    /// let d = date(2024, 2, 29);
591    /// assert_eq!(d.first_of_month(), date(2024, 2, 1));
592    /// ```
593    #[inline]
594    pub fn first_of_month(self) -> Date {
595        Date::from_jcore(self.inner.first_of_month())
596    }
597
598    /// Returns the last date of the month that this date resides in.
599    ///
600    /// # Example
601    ///
602    /// ```
603    /// use jiff::civil::date;
604    ///
605    /// let d = date(2024, 2, 5);
606    /// assert_eq!(d.last_of_month(), date(2024, 2, 29));
607    /// ```
608    #[inline]
609    pub fn last_of_month(self) -> Date {
610        Date::from_jcore(self.inner.last_of_month())
611    }
612
613    /// Returns the total number of days in the the month in which this date
614    /// resides.
615    ///
616    /// This is guaranteed to always return one of the following values,
617    /// depending on the year and the month: 28, 29, 30 or 31.
618    ///
619    /// # Example
620    ///
621    /// ```
622    /// use jiff::civil::date;
623    ///
624    /// let d = date(2024, 2, 10);
625    /// assert_eq!(d.days_in_month(), 29);
626    ///
627    /// let d = date(2023, 2, 10);
628    /// assert_eq!(d.days_in_month(), 28);
629    ///
630    /// let d = date(2024, 8, 15);
631    /// assert_eq!(d.days_in_month(), 31);
632    /// ```
633    #[inline]
634    pub fn days_in_month(self) -> i8 {
635        self.inner.days_in_month()
636    }
637
638    /// Returns the first date of the year that this date resides in.
639    ///
640    /// # Example
641    ///
642    /// ```
643    /// use jiff::civil::date;
644    ///
645    /// let d = date(2024, 2, 29);
646    /// assert_eq!(d.first_of_year(), date(2024, 1, 1));
647    /// ```
648    #[inline]
649    pub fn first_of_year(self) -> Date {
650        Date::from_jcore(self.inner.first_of_year())
651    }
652
653    /// Returns the last date of the year that this date resides in.
654    ///
655    /// # Example
656    ///
657    /// ```
658    /// use jiff::civil::date;
659    ///
660    /// let d = date(2024, 2, 5);
661    /// assert_eq!(d.last_of_year(), date(2024, 12, 31));
662    /// ```
663    #[inline]
664    pub fn last_of_year(self) -> Date {
665        Date::from_jcore(self.inner.last_of_year())
666    }
667
668    /// Returns the total number of days in the the year in which this date
669    /// resides.
670    ///
671    /// This is guaranteed to always return either `365` or `366`.
672    ///
673    /// # Example
674    ///
675    /// ```
676    /// use jiff::civil::date;
677    ///
678    /// let d = date(2024, 7, 10);
679    /// assert_eq!(d.days_in_year(), 366);
680    ///
681    /// let d = date(2023, 7, 10);
682    /// assert_eq!(d.days_in_year(), 365);
683    /// ```
684    #[inline]
685    pub fn days_in_year(self) -> i16 {
686        self.inner.days_in_year()
687    }
688
689    /// Returns true if and only if the year in which this date resides is a
690    /// leap year.
691    ///
692    /// # Example
693    ///
694    /// ```
695    /// use jiff::civil::date;
696    ///
697    /// assert!(date(2024, 1, 1).in_leap_year());
698    /// assert!(!date(2023, 12, 31).in_leap_year());
699    /// ```
700    #[inline]
701    pub fn in_leap_year(self) -> bool {
702        self.inner.in_leap_year()
703    }
704
705    /// Returns the date immediately following this one.
706    ///
707    /// # Errors
708    ///
709    /// This returns an error when this date is the maximum value.
710    ///
711    /// # Example
712    ///
713    /// ```
714    /// use jiff::civil::{Date, date};
715    ///
716    /// let d = date(2024, 2, 28);
717    /// assert_eq!(d.tomorrow()?, date(2024, 2, 29));
718    ///
719    /// // The max doesn't have a tomorrow.
720    /// assert!(Date::MAX.tomorrow().is_err());
721    ///
722    /// # Ok::<(), Box<dyn std::error::Error>>(())
723    /// ```
724    #[inline]
725    pub fn tomorrow(self) -> Result<Date, Error> {
726        self.inner.tomorrow().map(Date::from_jcore).map_err(Error::jcore_range)
727    }
728
729    /// Returns the date immediately preceding this one.
730    ///
731    /// # Errors
732    ///
733    /// This returns an error when this date is the minimum value.
734    ///
735    /// # Example
736    ///
737    /// ```
738    /// use jiff::civil::{Date, date};
739    ///
740    /// let d = date(2024, 3, 1);
741    /// assert_eq!(d.yesterday()?, date(2024, 2, 29));
742    ///
743    /// // The min doesn't have a yesterday.
744    /// assert!(Date::MIN.yesterday().is_err());
745    ///
746    /// # Ok::<(), Box<dyn std::error::Error>>(())
747    /// ```
748    #[inline]
749    pub fn yesterday(self) -> Result<Date, Error> {
750        self.inner
751            .yesterday()
752            .map(Date::from_jcore)
753            .map_err(Error::jcore_range)
754    }
755
756    /// Returns the "nth" weekday from the beginning or end of the month in
757    /// which this date resides.
758    ///
759    /// The `nth` parameter can be positive or negative. A positive value
760    /// computes the "nth" weekday from the beginning of the month. A negative
761    /// value computes the "nth" weekday from the end of the month. So for
762    /// example, use `-1` to "find the last weekday" in this date's month.
763    ///
764    /// # Errors
765    ///
766    /// This returns an error when `nth` is `0`, or if it is `5` or `-5` and
767    /// there is no 5th weekday from the beginning or end of the month.
768    ///
769    /// # Example
770    ///
771    /// This shows how to get the nth weekday in a month, starting from the
772    /// beginning of the month:
773    ///
774    /// ```
775    /// use jiff::civil::{Weekday, date};
776    ///
777    /// let month = date(2017, 3, 1);
778    /// let second_friday = month.nth_weekday_of_month(2, Weekday::Friday)?;
779    /// assert_eq!(second_friday, date(2017, 3, 10));
780    ///
781    /// # Ok::<(), Box<dyn std::error::Error>>(())
782    /// ```
783    ///
784    /// This shows how to do the reverse of the above. That is, the nth _last_
785    /// weekday in a month:
786    ///
787    /// ```
788    /// use jiff::civil::{Weekday, date};
789    ///
790    /// let month = date(2024, 3, 1);
791    /// let last_thursday = month.nth_weekday_of_month(-1, Weekday::Thursday)?;
792    /// assert_eq!(last_thursday, date(2024, 3, 28));
793    /// let second_last_thursday = month.nth_weekday_of_month(
794    ///     -2,
795    ///     Weekday::Thursday,
796    /// )?;
797    /// assert_eq!(second_last_thursday, date(2024, 3, 21));
798    ///
799    /// # Ok::<(), Box<dyn std::error::Error>>(())
800    /// ```
801    ///
802    /// This routine can return an error if there isn't an `nth` weekday
803    /// for this month. For example, March 2024 only has 4 Mondays:
804    ///
805    /// ```
806    /// use jiff::civil::{Weekday, date};
807    ///
808    /// let month = date(2024, 3, 25);
809    /// let fourth_monday = month.nth_weekday_of_month(4, Weekday::Monday)?;
810    /// assert_eq!(fourth_monday, date(2024, 3, 25));
811    /// // There is no 5th Monday.
812    /// assert!(month.nth_weekday_of_month(5, Weekday::Monday).is_err());
813    /// // Same goes for counting backwards.
814    /// assert!(month.nth_weekday_of_month(-5, Weekday::Monday).is_err());
815    ///
816    /// # Ok::<(), Box<dyn std::error::Error>>(())
817    /// ```
818    #[inline]
819    pub fn nth_weekday_of_month(
820        self,
821        nth: i8,
822        weekday: Weekday,
823    ) -> Result<Date, Error> {
824        self.inner
825            .nth_weekday_of_month(nth, weekday.to_jcore())
826            .map(Date::from_jcore)
827            .map_err(Error::jcore_range)
828    }
829
830    /// Returns the "nth" weekday from this date, not including itself.
831    ///
832    /// The `nth` parameter can be positive or negative. A positive value
833    /// computes the "nth" weekday starting at the day after this date and
834    /// going forwards in time. A negative value computes the "nth" weekday
835    /// starting at the day before this date and going backwards in time.
836    ///
837    /// For example, if this date's weekday is a Sunday and the first Sunday is
838    /// asked for (that is, `date.nth_weekday(1, Weekday::Sunday)`), then the
839    /// result is a week from this date corresponding to the following Sunday.
840    ///
841    /// # Errors
842    ///
843    /// This returns an error when `nth` is `0`, or if it would otherwise
844    /// result in a date that overflows the minimum/maximum values of `Date`.
845    ///
846    /// # Example
847    ///
848    /// This example shows how to find the "nth" weekday going forwards in
849    /// time:
850    ///
851    /// ```
852    /// use jiff::civil::{Weekday, date};
853    ///
854    /// // Use a Sunday in March as our start date.
855    /// let d = date(2024, 3, 10);
856    /// assert_eq!(d.weekday(), Weekday::Sunday);
857    ///
858    /// // The first next Monday is tomorrow!
859    /// let next_monday = d.nth_weekday(1, Weekday::Monday)?;
860    /// assert_eq!(next_monday, date(2024, 3, 11));
861    ///
862    /// // But the next Sunday is a week away, because this doesn't
863    /// // include the current weekday.
864    /// let next_sunday = d.nth_weekday(1, Weekday::Sunday)?;
865    /// assert_eq!(next_sunday, date(2024, 3, 17));
866    ///
867    /// // "not this Thursday, but next Thursday"
868    /// let next_next_thursday = d.nth_weekday(2, Weekday::Thursday)?;
869    /// assert_eq!(next_next_thursday, date(2024, 3, 21));
870    ///
871    /// # Ok::<(), Box<dyn std::error::Error>>(())
872    /// ```
873    ///
874    /// This example shows how to find the "nth" weekday going backwards in
875    /// time:
876    ///
877    /// ```
878    /// use jiff::civil::{Weekday, date};
879    ///
880    /// // Use a Sunday in March as our start date.
881    /// let d = date(2024, 3, 10);
882    /// assert_eq!(d.weekday(), Weekday::Sunday);
883    ///
884    /// // "last Saturday" was yesterday!
885    /// let last_saturday = d.nth_weekday(-1, Weekday::Saturday)?;
886    /// assert_eq!(last_saturday, date(2024, 3, 9));
887    ///
888    /// // "last Sunday" was a week ago.
889    /// let last_sunday = d.nth_weekday(-1, Weekday::Sunday)?;
890    /// assert_eq!(last_sunday, date(2024, 3, 3));
891    ///
892    /// // "not last Thursday, but the one before"
893    /// let prev_prev_thursday = d.nth_weekday(-2, Weekday::Thursday)?;
894    /// assert_eq!(prev_prev_thursday, date(2024, 2, 29));
895    ///
896    /// # Ok::<(), Box<dyn std::error::Error>>(())
897    /// ```
898    ///
899    /// This example shows that overflow results in an error in either
900    /// direction:
901    ///
902    /// ```
903    /// use jiff::civil::{Date, Weekday};
904    ///
905    /// let d = Date::MAX;
906    /// assert_eq!(d.weekday(), Weekday::Friday);
907    /// assert!(d.nth_weekday(1, Weekday::Saturday).is_err());
908    ///
909    /// let d = Date::MIN;
910    /// assert_eq!(d.weekday(), Weekday::Monday);
911    /// assert!(d.nth_weekday(-1, Weekday::Sunday).is_err());
912    /// ```
913    ///
914    /// # Example: the start of Israeli summer time
915    ///
916    /// Israeli law says (at present, as of 2024-03-11) that DST or "summer
917    /// time" starts on the Friday before the last Sunday in March. We can find
918    /// that date using both `nth_weekday` and [`Date::nth_weekday_of_month`]:
919    ///
920    /// ```
921    /// use jiff::civil::{Weekday, date};
922    ///
923    /// let march = date(2024, 3, 1);
924    /// let last_sunday = march.nth_weekday_of_month(-1, Weekday::Sunday)?;
925    /// let dst_starts_on = last_sunday.nth_weekday(-1, Weekday::Friday)?;
926    /// assert_eq!(dst_starts_on, date(2024, 3, 29));
927    ///
928    /// # Ok::<(), Box<dyn std::error::Error>>(())
929    /// ```
930    ///
931    /// # Example: getting the start of the week
932    ///
933    /// Given a date, one can use `nth_weekday` to determine the start of the
934    /// week in which the date resides in. This might vary based on whether
935    /// the weeks start on Sunday or Monday. This example shows how to handle
936    /// both.
937    ///
938    /// ```
939    /// use jiff::civil::{Weekday, date};
940    ///
941    /// let d = date(2024, 3, 15);
942    /// // For weeks starting with Sunday.
943    /// let start_of_week = d.tomorrow()?.nth_weekday(-1, Weekday::Sunday)?;
944    /// assert_eq!(start_of_week, date(2024, 3, 10));
945    /// // For weeks starting with Monday.
946    /// let start_of_week = d.tomorrow()?.nth_weekday(-1, Weekday::Monday)?;
947    /// assert_eq!(start_of_week, date(2024, 3, 11));
948    ///
949    /// # Ok::<(), Box<dyn std::error::Error>>(())
950    /// ```
951    ///
952    /// In the above example, we first get the date after the current one
953    /// because `nth_weekday` does not consider itself when counting. This
954    /// works as expected even at the boundaries of a week:
955    ///
956    /// ```
957    /// use jiff::civil::{Weekday, date};
958    ///
959    /// // The start of the week.
960    /// let d = date(2024, 3, 10);
961    /// let start_of_week = d.tomorrow()?.nth_weekday(-1, Weekday::Sunday)?;
962    /// assert_eq!(start_of_week, date(2024, 3, 10));
963    /// // The end of the week.
964    /// let d = date(2024, 3, 16);
965    /// let start_of_week = d.tomorrow()?.nth_weekday(-1, Weekday::Sunday)?;
966    /// assert_eq!(start_of_week, date(2024, 3, 10));
967    ///
968    /// # Ok::<(), Box<dyn std::error::Error>>(())
969    /// ```
970    #[inline]
971    pub fn nth_weekday(
972        self,
973        nth: i32,
974        weekday: Weekday,
975    ) -> Result<Date, Error> {
976        self.inner
977            .nth_weekday(nth, weekday.to_jcore())
978            .map(Date::from_jcore)
979            .map_err(Error::jcore_range)
980    }
981
982    /// Construct an [ISO 8601 week date] from this Gregorian date.
983    ///
984    /// The [`ISOWeekDate`] type describes itself in more detail, but in
985    /// brief, the ISO week date calendar system eschews months in favor of
986    /// weeks.
987    ///
988    /// The minimum and maximum values of an `ISOWeekDate` correspond
989    /// precisely to the minimum and maximum values of a `Date`. Therefore,
990    /// converting between them is lossless and infallible.
991    ///
992    /// This routine is equivalent to [`ISOWeekDate::from_date`].
993    ///
994    /// [ISO 8601 week date]: https://en.wikipedia.org/wiki/ISO_week_date
995    ///
996    /// # Example
997    ///
998    /// This shows a number of examples demonstrating the conversion from a
999    /// Gregorian date to an ISO 8601 week date:
1000    ///
1001    /// ```
1002    /// use jiff::civil::{Date, Weekday, date};
1003    ///
1004    /// let weekdate = date(1995, 1, 1).iso_week_date();
1005    /// assert_eq!(weekdate.year(), 1994);
1006    /// assert_eq!(weekdate.week(), 52);
1007    /// assert_eq!(weekdate.weekday(), Weekday::Sunday);
1008    ///
1009    /// let weekdate = date(1996, 12, 31).iso_week_date();
1010    /// assert_eq!(weekdate.year(), 1997);
1011    /// assert_eq!(weekdate.week(), 1);
1012    /// assert_eq!(weekdate.weekday(), Weekday::Tuesday);
1013    ///
1014    /// let weekdate = date(2019, 12, 30).iso_week_date();
1015    /// assert_eq!(weekdate.year(), 2020);
1016    /// assert_eq!(weekdate.week(), 1);
1017    /// assert_eq!(weekdate.weekday(), Weekday::Monday);
1018    ///
1019    /// let weekdate = date(2024, 3, 9).iso_week_date();
1020    /// assert_eq!(weekdate.year(), 2024);
1021    /// assert_eq!(weekdate.week(), 10);
1022    /// assert_eq!(weekdate.weekday(), Weekday::Saturday);
1023    ///
1024    /// let weekdate = Date::MIN.iso_week_date();
1025    /// assert_eq!(weekdate.year(), -9999);
1026    /// assert_eq!(weekdate.week(), 1);
1027    /// assert_eq!(weekdate.weekday(), Weekday::Monday);
1028    ///
1029    /// let weekdate = Date::MAX.iso_week_date();
1030    /// assert_eq!(weekdate.year(), 9999);
1031    /// assert_eq!(weekdate.week(), 52);
1032    /// assert_eq!(weekdate.weekday(), Weekday::Friday);
1033    /// ```
1034    #[inline]
1035    pub fn iso_week_date(self) -> ISOWeekDate {
1036        ISOWeekDate::from_jcore(self.inner.to_iso_week_date())
1037    }
1038
1039    /// Converts a civil date to a [`ZonedDateTime`] datetime by adding the
1040    /// given time zone and setting the clock time to midnight.
1041    ///
1042    /// This is a convenience function for
1043    /// `date.to_datetime(midnight).in_tz(name)`. See
1044    /// [`DateTime::to_zoned_datetime`] for more details. Note that ambiguous
1045    /// datetimes are handled in the same way as
1046    /// `DateTime::to_zoned_datetime`.
1047    ///
1048    /// # Errors
1049    ///
1050    /// This returns an error when the given time zone name could not be found
1051    /// in the default time zone database.
1052    ///
1053    /// This also returns an error if this date could not be represented as
1054    /// a timestamp. This can occur in some cases near the minimum and maximum
1055    /// boundaries of a `Date`.
1056    ///
1057    /// # Example
1058    ///
1059    /// This is a simple example of converting a civil date (a "wall" or
1060    /// "local" or "naive" date) to a precise instant in time that is aware of
1061    /// its time zone:
1062    ///
1063    /// ```
1064    /// use jiff::civil::date;
1065    ///
1066    /// let zdt = date(2024, 6, 20).in_tz("America/New_York")?;
1067    /// assert_eq!(zdt.to_string(), "2024-06-20T00:00:00-04:00[America/New_York]");
1068    ///
1069    /// # Ok::<(), Box<dyn std::error::Error>>(())
1070    /// ```
1071    ///
1072    /// # Example: dealing with ambiguity
1073    ///
1074    /// Since a [`ZonedDateTime`] corresponds to a precise instant in time (to
1075    /// nanosecond precision) and a `Date` can be many possible such instants,
1076    /// this routine chooses one for this date: the first one, or midnight.
1077    ///
1078    /// Interestingly, some regions implement their daylight saving time
1079    /// transitions at midnight. This means there are some places in the world
1080    /// where, once a year, midnight does not exist on their clocks. As a
1081    /// result, it's possible for the datetime string representing a
1082    /// [`ZonedDateTime`] to be something other than midnight. For example:
1083    ///
1084    /// ```
1085    /// use jiff::civil::date;
1086    ///
1087    /// let zdt = date(2024, 3, 10).in_tz("America/Havana")?;
1088    /// assert_eq!(
1089    ///     zdt.to_string(),
1090    ///     "2024-03-10T01:00:00-04:00[America/Havana]",
1091    /// );
1092    ///
1093    /// # Ok::<(), Box<dyn std::error::Error>>(())
1094    /// ```
1095    ///
1096    /// Since this uses
1097    /// [`Disambiguation::Compatible`](crate::tz::Disambiguation::Compatible),
1098    /// and since that also chooses the "later" time in a forward transition,
1099    /// it follows that the date of the returned `ZonedDateTime` will always
1100    /// match this civil date. (Unless there is a pathological time zone with a
1101    /// 24+ hour transition forward.)
1102    ///
1103    /// But if a different disambiguation strategy is used, even when only
1104    /// dealing with standard one hour transitions, the date returned can be
1105    /// different:
1106    ///
1107    /// ```
1108    /// use jiff::{civil::date, tz::TimeZone};
1109    ///
1110    /// let tz = TimeZone::get("America/Havana")?;
1111    /// let dt = date(2024, 3, 10).at(0, 0, 0, 0);
1112    /// let zdt = tz.to_ambiguous_zoned_datetime(dt).earlier()?;
1113    /// assert_eq!(
1114    ///     zdt.to_string(),
1115    ///     "2024-03-09T23:00:00-05:00[America/Havana]",
1116    /// );
1117    ///
1118    /// # Ok::<(), Box<dyn std::error::Error>>(())
1119    /// ```
1120    #[inline]
1121    pub fn in_tz(self, time_zone_name: &str) -> Result<ZonedDateTime, Error> {
1122        let tz = crate::tz::db().get(time_zone_name)?;
1123        self.to_zoned_datetime(tz)
1124    }
1125
1126    /// Converts a civil datetime to a [`ZonedDateTime`] datetime by adding the
1127    /// given [`TimeZone`] and setting the clock time to midnight.
1128    ///
1129    /// This is a convenience function for
1130    /// `date.to_datetime(midnight).to_zoned_datetime(tz)`. See
1131    /// [`DateTime::to_zoned_datetime`] for more details. Note that ambiguous
1132    /// datetimes are handled in the same way as
1133    /// `DateTime::to_zoned_datetime`.
1134    ///
1135    /// In the common case of a time zone being represented as a name string,
1136    /// like `Australia/Tasmania`, consider using [`Date::in_tz`]
1137    /// instead.
1138    ///
1139    /// # Errors
1140    ///
1141    /// This returns an error if this date could not be represented as a
1142    /// timestamp. This can occur in some cases near the minimum and maximum
1143    /// boundaries of a `Date`.
1144    ///
1145    /// # Example
1146    ///
1147    /// This example shows how to create a zoned value with a fixed time zone
1148    /// offset:
1149    ///
1150    /// ```
1151    /// use jiff::{civil::date, tz};
1152    ///
1153    /// let tz = tz::offset(-4).to_time_zone();
1154    /// let zdt = date(2024, 6, 20).to_zoned_datetime(tz)?;
1155    /// // A time zone annotation is still included in the printable version
1156    /// // of the ZonedDateTime value, but it is fixed to a particular offset.
1157    /// assert_eq!(zdt.to_string(), "2024-06-20T00:00:00-04:00[-04:00]");
1158    ///
1159    /// # Ok::<(), Box<dyn std::error::Error>>(())
1160    /// ```
1161    #[inline]
1162    pub fn to_zoned_datetime(
1163        self,
1164        tz: TimeZone,
1165    ) -> Result<ZonedDateTime, Error> {
1166        DateTime::from(self).to_zoned_datetime(tz)
1167    }
1168
1169    /// Given a [`Time`], this constructs a [`DateTime`] value with its time
1170    /// component equal to this time.
1171    ///
1172    /// This is a convenience function for [`DateTime::from_parts`].
1173    ///
1174    /// # Example
1175    ///
1176    /// ```
1177    /// use jiff::civil::{DateTime, date, time};
1178    ///
1179    /// let date = date(2010, 3, 14);
1180    /// let time = time(2, 30, 0, 0);
1181    /// assert_eq!(DateTime::from_parts(date, time), date.to_datetime(time));
1182    /// ```
1183    #[inline]
1184    pub const fn to_datetime(self, time: Time) -> DateTime {
1185        DateTime::from_parts(self, time)
1186    }
1187
1188    /// A convenience function for constructing a [`DateTime`] from this date
1189    /// at the time given by its components.
1190    ///
1191    /// # Panics
1192    ///
1193    /// This panics if the provided values do not correspond to a valid `Time`.
1194    /// All of the following conditions must be true:
1195    ///
1196    /// * `0 <= hour <= 23`
1197    /// * `0 <= minute <= 59`
1198    /// * `0 <= second <= 59`
1199    /// * `0 <= subsec_nanosecond <= 999,999,999`
1200    ///
1201    /// Similarly, when used in a const context, invalid parameters will
1202    /// prevent your Rust program from compiling.
1203    ///
1204    /// # Example
1205    ///
1206    /// ```
1207    /// use jiff::civil::date;
1208    ///
1209    /// assert_eq!(
1210    ///     date(2010, 3, 14).at(2, 30, 0, 0).to_string(),
1211    ///     "2010-03-14T02:30:00",
1212    /// );
1213    /// ```
1214    ///
1215    /// One can also flip the order by making use of [`Time::on`]:
1216    ///
1217    /// ```
1218    /// use jiff::civil::time;
1219    ///
1220    /// assert_eq!(
1221    ///     time(2, 30, 0, 0).on(2010, 3, 14).to_string(),
1222    ///     "2010-03-14T02:30:00",
1223    /// );
1224    /// ```
1225    #[inline]
1226    pub const fn at(
1227        self,
1228        hour: i8,
1229        minute: i8,
1230        second: i8,
1231        subsec_nanosecond: i32,
1232    ) -> DateTime {
1233        DateTime::from_parts(
1234            self,
1235            Time::constant(hour, minute, second, subsec_nanosecond),
1236        )
1237    }
1238
1239    /// Add the given span of time to this date. If the sum would overflow the
1240    /// minimum or maximum date values, then an error is returned.
1241    ///
1242    /// This operation accepts three different duration types: [`Span`],
1243    /// [`SignedDuration`] or [`std::time::Duration`]. This is achieved via
1244    /// `From` trait implementations for the [`DateArithmetic`] type.
1245    ///
1246    /// # Properties
1247    ///
1248    /// When adding a [`Span`] duration, this routine is _not_ reversible
1249    /// because some additions may be ambiguous. For example, adding `1 month`
1250    /// to the date `2024-03-31` will produce `2024-04-30` since April has only
1251    /// 30 days in a month. Conversely, subtracting `1 month` from `2024-04-30`
1252    /// will produce `2024-03-30`, which is not the date we started with.
1253    ///
1254    /// If spans of time are limited to units of days (or less), then this
1255    /// routine _is_ reversible. This also implies that all operations with
1256    /// a [`SignedDuration`] or a [`std::time::Duration`] are reversible.
1257    ///
1258    /// # Errors
1259    ///
1260    /// If the span added to this date would result in a date that exceeds the
1261    /// range of a `Date`, then this will return an error.
1262    ///
1263    /// # Examples
1264    ///
1265    /// This shows a few examples of adding spans of time to various dates.
1266    /// We make use of the [`ToSpan`](crate::ToSpan) trait for convenient
1267    /// creation of spans.
1268    ///
1269    /// ```
1270    /// use jiff::{civil::date, ToSpan};
1271    ///
1272    /// let d = date(2024, 3, 31);
1273    /// assert_eq!(d.checked_add(1.months())?, date(2024, 4, 30));
1274    /// // Adding two months gives us May 31, not May 30.
1275    /// let d = date(2024, 3, 31);
1276    /// assert_eq!(d.checked_add(2.months())?, date(2024, 5, 31));
1277    /// // Any time in the span that does not exceed a day is ignored.
1278    /// let d = date(2024, 3, 31);
1279    /// assert_eq!(d.checked_add(23.hours())?, date(2024, 3, 31));
1280    /// // But if the time exceeds a day, that is accounted for!
1281    /// let d = date(2024, 3, 31);
1282    /// assert_eq!(d.checked_add(28.hours())?, date(2024, 4, 1));
1283    ///
1284    /// # Ok::<(), Box<dyn std::error::Error>>(())
1285    /// ```
1286    ///
1287    /// # Example: available via addition operator
1288    ///
1289    /// This routine can be used via the `+` operator. Note though that if it
1290    /// fails, it will result in a panic.
1291    ///
1292    /// ```
1293    /// use jiff::{civil::date, ToSpan};
1294    ///
1295    /// let d = date(2024, 3, 31);
1296    /// assert_eq!(d + 1.months(), date(2024, 4, 30));
1297    /// ```
1298    ///
1299    /// # Example: negative spans are supported
1300    ///
1301    /// ```
1302    /// use jiff::{civil::date, ToSpan};
1303    ///
1304    /// let d = date(2024, 3, 31);
1305    /// assert_eq!(
1306    ///     d.checked_add(-1.months())?,
1307    ///     date(2024, 2, 29),
1308    /// );
1309    /// # Ok::<(), Box<dyn std::error::Error>>(())
1310    /// ```
1311    ///
1312    /// # Example: error on overflow
1313    ///
1314    /// ```
1315    /// use jiff::{civil::date, ToSpan};
1316    ///
1317    /// let d = date(2024, 3, 31);
1318    /// assert!(d.checked_add(9000.years()).is_err());
1319    /// assert!(d.checked_add(-19000.years()).is_err());
1320    /// ```
1321    ///
1322    /// # Example: adding absolute durations
1323    ///
1324    /// This shows how to add signed and unsigned absolute durations to a
1325    /// `Date`. Only whole numbers of days are considered. Since this is a
1326    /// civil date unaware of time zones, days are always 24 hours.
1327    ///
1328    /// ```
1329    /// use std::time::Duration;
1330    ///
1331    /// use jiff::{civil::date, SignedDuration};
1332    ///
1333    /// let d = date(2024, 2, 29);
1334    ///
1335    /// let dur = SignedDuration::from_hours(24);
1336    /// assert_eq!(d.checked_add(dur)?, date(2024, 3, 1));
1337    /// assert_eq!(d.checked_add(-dur)?, date(2024, 2, 28));
1338    ///
1339    /// // Any leftover time is truncated. That is, only
1340    /// // whole days from the duration are considered.
1341    /// let dur = Duration::from_secs((24 * 60 * 60) + (23 * 60 * 60));
1342    /// assert_eq!(d.checked_add(dur)?, date(2024, 3, 1));
1343    ///
1344    /// # Ok::<(), Box<dyn std::error::Error>>(())
1345    /// ```
1346    #[inline]
1347    pub fn checked_add<A: Into<DateArithmetic>>(
1348        self,
1349        duration: A,
1350    ) -> Result<Date, Error> {
1351        let duration: DateArithmetic = duration.into();
1352        duration.checked_add(self)
1353    }
1354
1355    #[inline]
1356    fn checked_add_span(self, span: &Span) -> Result<Date, Error> {
1357        if span.is_zero() {
1358            return Ok(self);
1359        }
1360        if span.units().contains_only(Unit::Day) {
1361            return self
1362                .inner
1363                .checked_add(span.get_days())
1364                .map(Date::from_jcore)
1365                .map_err(Error::jcore_range);
1366        }
1367
1368        let (month, years) =
1369            month_add_overflowing(self.month(), span.get_months());
1370        let year = b::Year::checked_add(self.year(), years)
1371            .and_then(|years| b::Year::checked_add(years, span.get_years()))?;
1372        let date = Date::new_constrain(year, month, self.day())?;
1373        let mut days = date
1374            .to_unix_epoch_day()
1375            .checked_add(7 * span.get_weeks())
1376            .and_then(|days| days.checked_add(span.get_days()))
1377            .map_err(Error::jcore_range)?;
1378        if !span.units().only_time().is_empty() {
1379            let time_days = b::UnixEpochDays::check(
1380                span.to_invariant_duration_time_only().as_civil_days(),
1381            )?;
1382            days = days.checked_add(time_days).map_err(Error::jcore_range)?;
1383        }
1384        Ok(Date::from_unix_epoch_day(days))
1385    }
1386
1387    #[inline]
1388    fn checked_add_duration(
1389        self,
1390        duration: SignedDuration,
1391    ) -> Result<Date, Error> {
1392        let days = b::UnixEpochDays::check(duration.as_civil_days())
1393            .context(E::OverflowDaysDuration)?;
1394        return self
1395            .inner
1396            .checked_add(days)
1397            .map(Date::from_jcore)
1398            .map_err(Error::jcore_range);
1399    }
1400
1401    /// This routine is identical to [`Date::checked_add`] with the duration
1402    /// negated.
1403    ///
1404    /// # Errors
1405    ///
1406    /// This has the same error conditions as [`Date::checked_add`].
1407    ///
1408    /// # Example
1409    ///
1410    /// ```
1411    /// use std::time::Duration;
1412    ///
1413    /// use jiff::{civil::date, SignedDuration, ToSpan};
1414    ///
1415    /// let d = date(2024, 2, 29);
1416    /// assert_eq!(d.checked_sub(1.year())?, date(2023, 2, 28));
1417    ///
1418    /// let dur = SignedDuration::from_hours(24);
1419    /// assert_eq!(d.checked_sub(dur)?, date(2024, 2, 28));
1420    ///
1421    /// let dur = Duration::from_secs(24 * 60 * 60);
1422    /// assert_eq!(d.checked_sub(dur)?, date(2024, 2, 28));
1423    ///
1424    /// # Ok::<(), Box<dyn std::error::Error>>(())
1425    /// ```
1426    #[inline]
1427    pub fn checked_sub<A: Into<DateArithmetic>>(
1428        self,
1429        duration: A,
1430    ) -> Result<Date, Error> {
1431        let duration: DateArithmetic = duration.into();
1432        duration.checked_neg().and_then(|da| da.checked_add(self))
1433    }
1434
1435    /// This routine is identical to [`Date::checked_add`], except the
1436    /// result saturates on overflow. That is, instead of overflow, either
1437    /// [`Date::MIN`] or [`Date::MAX`] is returned.
1438    ///
1439    /// # Example
1440    ///
1441    /// ```
1442    /// use jiff::{civil::{Date, date}, SignedDuration, ToSpan};
1443    ///
1444    /// let d = date(2024, 3, 31);
1445    /// assert_eq!(Date::MAX, d.saturating_add(9000.years()));
1446    /// assert_eq!(Date::MIN, d.saturating_add(-19000.years()));
1447    /// assert_eq!(Date::MAX, d.saturating_add(SignedDuration::MAX));
1448    /// assert_eq!(Date::MIN, d.saturating_add(SignedDuration::MIN));
1449    /// assert_eq!(Date::MAX, d.saturating_add(std::time::Duration::MAX));
1450    /// ```
1451    #[inline]
1452    pub fn saturating_add<A: Into<DateArithmetic>>(self, duration: A) -> Date {
1453        let duration: DateArithmetic = duration.into();
1454        self.checked_add(duration).unwrap_or_else(|_| {
1455            if duration.is_negative() { Date::MIN } else { Date::MAX }
1456        })
1457    }
1458
1459    /// This routine is identical to [`Date::saturating_add`] with the span
1460    /// parameter negated.
1461    ///
1462    /// # Example
1463    ///
1464    /// ```
1465    /// use jiff::{civil::{Date, date}, SignedDuration, ToSpan};
1466    ///
1467    /// let d = date(2024, 3, 31);
1468    /// assert_eq!(Date::MIN, d.saturating_sub(19000.years()));
1469    /// assert_eq!(Date::MAX, d.saturating_sub(-9000.years()));
1470    /// assert_eq!(Date::MIN, d.saturating_sub(SignedDuration::MAX));
1471    /// assert_eq!(Date::MAX, d.saturating_sub(SignedDuration::MIN));
1472    /// assert_eq!(Date::MIN, d.saturating_sub(std::time::Duration::MAX));
1473    /// ```
1474    #[inline]
1475    pub fn saturating_sub<A: Into<DateArithmetic>>(self, duration: A) -> Date {
1476        let duration: DateArithmetic = duration.into();
1477        let Ok(duration) = duration.checked_neg() else { return Date::MIN };
1478        self.saturating_add(duration)
1479    }
1480
1481    /// Returns a span representing the elapsed time from this date until
1482    /// the given `other` date.
1483    ///
1484    /// When `other` occurs before this date, then the span returned will be
1485    /// negative.
1486    ///
1487    /// Depending on the input provided, the span returned is rounded. It may
1488    /// also be balanced up to bigger units than the default. By default, the
1489    /// span returned is balanced such that the biggest and smallest possible
1490    /// unit is days.
1491    ///
1492    /// This operation is configured by providing a [`DateDifference`]
1493    /// value. Since this routine accepts anything that implements
1494    /// `Into<DateDifference>`, once can pass a `Date` directly. One
1495    /// can also pass a `(Unit, Date)`, where `Unit` is treated as
1496    /// [`DateDifference::largest`].
1497    ///
1498    /// # Properties
1499    ///
1500    /// It is guaranteed that if the returned span is subtracted from `other`,
1501    /// and if no rounding is requested, and if the largest unit request is at
1502    /// most `Unit::Day`, then the original date will be returned.
1503    ///
1504    /// This routine is equivalent to `self.since(other).map(|span| -span)`
1505    /// if no rounding options are set. If rounding options are set, then
1506    /// it's equivalent to
1507    /// `self.since(other_without_rounding_options).map(|span| -span)`,
1508    /// followed by a call to [`Span::round`] with the appropriate rounding
1509    /// options set. This is because the negation of a span can result in
1510    /// different rounding results depending on the rounding mode.
1511    ///
1512    /// # Errors
1513    ///
1514    /// An error can occur if `DateDifference` is misconfigured. For example,
1515    /// if the smallest unit provided is bigger than the largest unit.
1516    ///
1517    /// It is guaranteed that if one provides a date with the default
1518    /// [`DateDifference`] configuration, then this routine will never fail.
1519    ///
1520    /// # Examples
1521    ///
1522    /// ```
1523    /// use jiff::{civil::date, ToSpan};
1524    ///
1525    /// let earlier = date(2006, 8, 24);
1526    /// let later = date(2019, 1, 31);
1527    /// assert_eq!(earlier.until(later)?, 4543.days().fieldwise());
1528    ///
1529    /// // Flipping the dates is fine, but you'll get a negative span.
1530    /// let earlier = date(2006, 8, 24);
1531    /// let later = date(2019, 1, 31);
1532    /// assert_eq!(later.until(earlier)?, -4543.days().fieldwise());
1533    ///
1534    /// # Ok::<(), Box<dyn std::error::Error>>(())
1535    /// ```
1536    ///
1537    /// # Example: using bigger units
1538    ///
1539    /// This example shows how to expand the span returned to bigger units.
1540    /// This makes use of a `From<(Unit, Date)> for DateDifference` trait
1541    /// implementation.
1542    ///
1543    /// ```
1544    /// use jiff::{civil::date, Unit, ToSpan};
1545    ///
1546    /// let d1 = date(1995, 12, 07);
1547    /// let d2 = date(2019, 01, 31);
1548    ///
1549    /// // The default limits durations to using "days" as the biggest unit.
1550    /// let span = d1.until(d2)?;
1551    /// assert_eq!(span.to_string(), "P8456D");
1552    ///
1553    /// // But we can ask for units all the way up to years.
1554    /// let span = d1.until((Unit::Year, d2))?;
1555    /// assert_eq!(span.to_string(), "P23Y1M24D");
1556    ///
1557    /// # Ok::<(), Box<dyn std::error::Error>>(())
1558    /// ```
1559    ///
1560    /// # Example: rounding the result
1561    ///
1562    /// This shows how one might find the difference between two dates and
1563    /// have the result rounded to the nearest month.
1564    ///
1565    /// In this case, we need to hand-construct a [`DateDifference`]
1566    /// in order to gain full configurability.
1567    ///
1568    /// ```
1569    /// use jiff::{civil::{date, DateDifference}, Unit, ToSpan};
1570    ///
1571    /// let d1 = date(1995, 12, 07);
1572    /// let d2 = date(2019, 02, 06);
1573    ///
1574    /// let span = d1.until(DateDifference::from(d2).smallest(Unit::Month))?;
1575    /// assert_eq!(span, 277.months().fieldwise());
1576    ///
1577    /// // Or even include years to make the span a bit more comprehensible.
1578    /// let span = d1.until(
1579    ///     DateDifference::from(d2)
1580    ///         .smallest(Unit::Month)
1581    ///         .largest(Unit::Year),
1582    /// )?;
1583    /// // Notice that we are one day shy of 23y2m. Rounding spans computed
1584    /// // between dates uses truncation by default.
1585    /// assert_eq!(span, 23.years().months(1).fieldwise());
1586    ///
1587    /// # Ok::<(), Box<dyn std::error::Error>>(())
1588    /// ```
1589    ///
1590    /// # Example: units biggers than days inhibit reversibility
1591    ///
1592    /// If you ask for units bigger than days, then adding the span
1593    /// returned to the `other` date is not guaranteed to result in the
1594    /// original date. For example:
1595    ///
1596    /// ```
1597    /// use jiff::{civil::date, Unit, ToSpan};
1598    ///
1599    /// let d1 = date(2024, 3, 2);
1600    /// let d2 = date(2024, 5, 1);
1601    ///
1602    /// let span = d1.until((Unit::Month, d2))?;
1603    /// assert_eq!(span, 1.month().days(29).fieldwise());
1604    /// let maybe_original = d2.checked_sub(span)?;
1605    /// // Not the same as the original datetime!
1606    /// assert_eq!(maybe_original, date(2024, 3, 3));
1607    ///
1608    /// // But in the default configuration, days are always the biggest unit
1609    /// // and reversibility is guaranteed.
1610    /// let span = d1.until(d2)?;
1611    /// assert_eq!(span, 60.days().fieldwise());
1612    /// let is_original = d2.checked_sub(span)?;
1613    /// assert_eq!(is_original, d1);
1614    ///
1615    /// # Ok::<(), Box<dyn std::error::Error>>(())
1616    /// ```
1617    ///
1618    /// This occurs because spans are added as if by adding the biggest units
1619    /// first, and then the smaller units. Because months vary in length,
1620    /// their meaning can change depending on how the span is added. In this
1621    /// case, adding one month to `2024-03-02` corresponds to 31 days, but
1622    /// subtracting one month from `2024-05-01` corresponds to 30 days.
1623    #[inline]
1624    pub fn until<A: Into<DateDifference>>(
1625        self,
1626        other: A,
1627    ) -> Result<Span, Error> {
1628        let args: DateDifference = other.into();
1629        let span = args.since_with_largest_unit(self)?;
1630        if args.rounding_may_change_span() {
1631            span.round(args.round.relative(self))
1632        } else {
1633            Ok(span)
1634        }
1635    }
1636
1637    /// This routine is identical to [`Date::until`], but the order of the
1638    /// parameters is flipped.
1639    ///
1640    /// # Errors
1641    ///
1642    /// This has the same error conditions as [`Date::until`].
1643    ///
1644    /// # Example
1645    ///
1646    /// This routine can be used via the `-` operator. Since the default
1647    /// configuration is used and because a `Span` can represent the difference
1648    /// between any two possible dates, it will never panic.
1649    ///
1650    /// ```
1651    /// use jiff::{civil::date, ToSpan};
1652    ///
1653    /// let earlier = date(2006, 8, 24);
1654    /// let later = date(2019, 1, 31);
1655    /// assert_eq!(later - earlier, 4543.days().fieldwise());
1656    /// // Equivalent to:
1657    /// assert_eq!(later.since(earlier).unwrap(), 4543.days().fieldwise());
1658    /// ```
1659    #[inline]
1660    pub fn since<A: Into<DateDifference>>(
1661        self,
1662        other: A,
1663    ) -> Result<Span, Error> {
1664        let args: DateDifference = other.into();
1665        let span = -args.since_with_largest_unit(self)?;
1666        if args.rounding_may_change_span() {
1667            span.round(args.round.relative(self))
1668        } else {
1669            Ok(span)
1670        }
1671    }
1672
1673    /// Returns an absolute duration representing the elapsed time from this
1674    /// date until the given `other` date.
1675    ///
1676    /// When `other` occurs before this date, then the duration returned will
1677    /// be negative.
1678    ///
1679    /// Unlike [`Date::until`], this returns a duration corresponding to a
1680    /// 96-bit integer of nanoseconds between two dates. In this case of
1681    /// computing durations between civil dates where all days are assumed to
1682    /// be 24 hours long, the duration returned will always be divisible by
1683    /// 24 hours. (That is, `24 * 60 * 60 * 1_000_000_000` nanoseconds.)
1684    ///
1685    /// # Fallibility
1686    ///
1687    /// This routine never panics or returns an error. Since there are no
1688    /// configuration options that can be incorrectly provided, no error is
1689    /// possible when calling this routine. In contrast, [`Date::until`] can
1690    /// return an error in some cases due to misconfiguration. But like this
1691    /// routine, [`Date::until`] never panics or returns an error in its
1692    /// default configuration.
1693    ///
1694    /// # When should I use this versus [`Date::until`]?
1695    ///
1696    /// See the type documentation for [`SignedDuration`] for the section on
1697    /// when one should use [`Span`] and when one should use `SignedDuration`.
1698    /// In short, use `Span` (and therefore `Date::until`) unless you have a
1699    /// specific reason to do otherwise.
1700    ///
1701    /// # Example
1702    ///
1703    /// ```
1704    /// use jiff::{civil::date, SignedDuration};
1705    ///
1706    /// let earlier = date(2006, 8, 24);
1707    /// let later = date(2019, 1, 31);
1708    /// assert_eq!(
1709    ///     earlier.duration_until(later),
1710    ///     SignedDuration::from_hours(4543 * 24),
1711    /// );
1712    /// ```
1713    ///
1714    /// # Example: difference with [`Date::until`]
1715    ///
1716    /// The main difference between this routine and `Date::until` is that the
1717    /// latter can return units other than a 96-bit integer of nanoseconds.
1718    /// While a 96-bit integer of nanoseconds can be converted into other
1719    /// units like hours, this can only be done for uniform units. (Uniform
1720    /// units are units for which each individual unit always corresponds to
1721    /// the same elapsed time regardless of the datetime it is relative to.)
1722    /// This can't be done for units like years, months or days without a
1723    /// relative date.
1724    ///
1725    /// ```
1726    /// use jiff::{civil::date, SignedDuration, Span, SpanRound, ToSpan, Unit};
1727    ///
1728    /// let d1 = date(2024, 1, 1);
1729    /// let d2 = date(2025, 4, 1);
1730    ///
1731    /// let span = d1.until((Unit::Year, d2))?;
1732    /// assert_eq!(span, 1.year().months(3).fieldwise());
1733    ///
1734    /// let duration = d1.duration_until(d2);
1735    /// assert_eq!(duration, SignedDuration::from_hours(456 * 24));
1736    /// // There's no way to extract years or months from the signed
1737    /// // duration like one might extract hours (because every hour
1738    /// // is the same length). Instead, you actually have to convert
1739    /// // it to a span and then balance it by providing a relative date!
1740    /// let options = SpanRound::new().largest(Unit::Year).relative(d1);
1741    /// let span = Span::try_from(duration)?.round(options)?;
1742    /// assert_eq!(span, 1.year().months(3).fieldwise());
1743    ///
1744    /// # Ok::<(), Box<dyn std::error::Error>>(())
1745    /// ```
1746    ///
1747    /// # Example: getting an unsigned duration
1748    ///
1749    /// If you're looking to find the duration between two dates as a
1750    /// [`std::time::Duration`], you'll need to use this method to get a
1751    /// [`SignedDuration`] and then convert it to a `std::time::Duration`:
1752    ///
1753    /// ```
1754    /// use std::time::Duration;
1755    ///
1756    /// use jiff::{civil::date, SignedDuration};
1757    ///
1758    /// let d1 = date(2024, 7, 1);
1759    /// let d2 = date(2024, 8, 1);
1760    /// let duration = Duration::try_from(d1.duration_until(d2))?;
1761    /// assert_eq!(duration, Duration::from_secs(31 * 24 * 60 * 60));
1762    ///
1763    /// // Note that unsigned durations cannot represent all
1764    /// // possible differences! If the duration would be negative,
1765    /// // then the conversion fails:
1766    /// assert!(Duration::try_from(d2.duration_until(d1)).is_err());
1767    ///
1768    /// # Ok::<(), Box<dyn std::error::Error>>(())
1769    /// ```
1770    #[inline]
1771    pub fn duration_until(self, other: Date) -> SignedDuration {
1772        SignedDuration::date_until(self, other)
1773    }
1774
1775    /// This routine is identical to [`Date::duration_until`], but the order of
1776    /// the parameters is flipped.
1777    ///
1778    /// # Example
1779    ///
1780    /// ```
1781    /// use jiff::{civil::date, SignedDuration};
1782    ///
1783    /// let earlier = date(2006, 8, 24);
1784    /// let later = date(2019, 1, 31);
1785    /// assert_eq!(
1786    ///     later.duration_since(earlier),
1787    ///     SignedDuration::from_hours(4543 * 24),
1788    /// );
1789    /// ```
1790    #[inline]
1791    pub fn duration_since(self, other: Date) -> SignedDuration {
1792        SignedDuration::date_until(other, self)
1793    }
1794
1795    /// Return an iterator of periodic dates determined by the given span.
1796    ///
1797    /// The given span may be negative, in which case, the iterator will move
1798    /// backwards through time. The iterator won't stop until either the span
1799    /// itself overflows, or it would otherwise exceed the minimum or maximum
1800    /// `Date` value.
1801    ///
1802    /// # Example: Halloween day of the week
1803    ///
1804    /// As a kid, I always hoped for Halloween to fall on a weekend. With this
1805    /// program, we can print the day of the week for all Halloweens in the
1806    /// 2020s.
1807    ///
1808    /// ```
1809    /// use jiff::{civil::{Weekday, date}, ToSpan};
1810    ///
1811    /// let start = date(2020, 10, 31);
1812    /// let mut halloween_days_of_week = vec![];
1813    /// for halloween in start.series(1.years()).take(10) {
1814    ///     halloween_days_of_week.push(
1815    ///         (halloween.year(), halloween.weekday()),
1816    ///     );
1817    /// }
1818    /// assert_eq!(halloween_days_of_week, vec![
1819    ///     (2020, Weekday::Saturday),
1820    ///     (2021, Weekday::Sunday),
1821    ///     (2022, Weekday::Monday),
1822    ///     (2023, Weekday::Tuesday),
1823    ///     (2024, Weekday::Thursday),
1824    ///     (2025, Weekday::Friday),
1825    ///     (2026, Weekday::Saturday),
1826    ///     (2027, Weekday::Sunday),
1827    ///     (2028, Weekday::Tuesday),
1828    ///     (2029, Weekday::Wednesday),
1829    /// ]);
1830    /// ```
1831    ///
1832    /// # Example: how many times do I mow the lawn in a year?
1833    ///
1834    /// I mow the lawn about every week and a half from the beginning of May
1835    /// to the end of October. About how many times will I mow the lawn in
1836    /// 2024?
1837    ///
1838    /// ```
1839    /// use jiff::{ToSpan, civil::date};
1840    ///
1841    /// let start = date(2024, 5, 1);
1842    /// let end = date(2024, 10, 31);
1843    /// let mows = start
1844    ///     .series(1.weeks().days(3).hours(12))
1845    ///     .take_while(|&d| d <= end)
1846    ///     .count();
1847    /// assert_eq!(mows, 18);
1848    /// ```
1849    ///
1850    /// # Example: a period less than a day
1851    ///
1852    /// Using a period less than a day works, but since this type exists at the
1853    /// granularity of a day, some dates may be repeated.
1854    ///
1855    /// ```
1856    /// use jiff::{civil::{Date, date}, ToSpan};
1857    ///
1858    /// let start = date(2024, 3, 11);
1859    /// let every_five_hours: Vec<Date> =
1860    ///     start.series(15.hours()).take(7).collect();
1861    /// assert_eq!(every_five_hours, vec![
1862    ///     date(2024, 3, 11),
1863    ///     date(2024, 3, 11),
1864    ///     date(2024, 3, 12),
1865    ///     date(2024, 3, 12),
1866    ///     date(2024, 3, 13),
1867    ///     date(2024, 3, 14),
1868    ///     date(2024, 3, 14),
1869    /// ]);
1870    /// ```
1871    ///
1872    /// # Example: finding the most recent Friday the 13th
1873    ///
1874    /// When did the most recent Friday the 13th occur?
1875    ///
1876    /// ```
1877    /// use jiff::{civil::{Weekday, date}, ToSpan};
1878    ///
1879    /// let start = date(2024, 3, 13);
1880    /// let mut found = None;
1881    /// for date in start.series(-1.months()) {
1882    ///     if date.weekday() == Weekday::Friday {
1883    ///         found = Some(date);
1884    ///         break;
1885    ///     }
1886    /// }
1887    /// assert_eq!(found, Some(date(2023, 10, 13)));
1888    /// ```
1889    #[inline]
1890    pub fn series(self, period: Span) -> DateSeries {
1891        DateSeries { start: self, period, step: 0 }
1892    }
1893}
1894
1895/// Parsing and formatting using a "printf"-style API.
1896impl Date {
1897    /// Parses a civil date in `input` matching the given `format`.
1898    ///
1899    /// The format string uses a "printf"-style API where conversion
1900    /// specifiers can be used as place holders to match components of
1901    /// a datetime. For details on the specifiers supported, see the
1902    /// [`fmt::strtime`] module documentation.
1903    ///
1904    /// # Errors
1905    ///
1906    /// This returns an error when parsing failed. This might happen because
1907    /// the format string itself was invalid, or because the input didn't match
1908    /// the format string.
1909    ///
1910    /// This also returns an error if there wasn't sufficient information to
1911    /// construct a civil date. For example, if an offset wasn't parsed.
1912    ///
1913    /// # Example
1914    ///
1915    /// This example shows how to parse a civil date:
1916    ///
1917    /// ```
1918    /// use jiff::civil::Date;
1919    ///
1920    /// // Parse an American date with a two-digit year.
1921    /// let date = Date::strptime("%m/%d/%y", "7/14/24")?;
1922    /// assert_eq!(date.to_string(), "2024-07-14");
1923    ///
1924    /// # Ok::<(), Box<dyn std::error::Error>>(())
1925    /// ```
1926    #[inline]
1927    pub fn strptime(
1928        format: impl AsRef<[u8]>,
1929        input: impl AsRef<[u8]>,
1930    ) -> Result<Date, Error> {
1931        fmt::strtime::parse(format, input).and_then(|tm| tm.to_date())
1932    }
1933
1934    /// Formats this civil date according to the given `format`.
1935    ///
1936    /// The format string uses a "printf"-style API where conversion
1937    /// specifiers can be used as place holders to format components of
1938    /// a datetime. For details on the specifiers supported, see the
1939    /// [`fmt::strtime`] module documentation.
1940    ///
1941    /// # Errors and panics
1942    ///
1943    /// This will never error or panic. In particular,
1944    /// [lenient mode](crate::fmt::strtime::Config::lenient) is enabled, which
1945    /// means that all possible strings have some non-error interpretation.
1946    /// Note that because of this, and since Jiff may add new conversion
1947    /// specifiers in the future, the behavior of a format string may change
1948    /// when it would otherwise be invalid.
1949    ///
1950    /// To format in a way that surfaces errors, use either
1951    /// [`fmt::strtime::format`] or [`fmt::strtime::BrokenDownTime::format`].
1952    ///
1953    /// # Example
1954    ///
1955    /// This example shows how to format a civil date:
1956    ///
1957    /// ```
1958    /// use jiff::civil::date;
1959    ///
1960    /// let date = date(2024, 7, 15);
1961    /// let string = date.strftime("%Y-%m-%d is a %A").to_string();
1962    /// assert_eq!(string, "2024-07-15 is a Monday");
1963    /// ```
1964    ///
1965    /// # Example: errors are silently ignored
1966    ///
1967    /// If the formatting string is malformed in some way, then it is silently
1968    /// ignored. For example, when using an invalid formatting directive:
1969    ///
1970    /// ```
1971    /// use jiff::civil::date;
1972    ///
1973    /// let date = date(2024, 7, 15);
1974    /// let string = date.strftime("%Y %").to_string();
1975    /// assert_eq!(string, "2024 %");
1976    /// ```
1977    ///
1978    /// If one wants to surface errors from a formatting string, use a lower
1979    /// level API:
1980    ///
1981    /// ```
1982    /// use jiff::civil::date;
1983    ///
1984    /// let date = date(2024, 7, 15);
1985    /// assert_eq!(
1986    ///     jiff::fmt::strtime::format("%Y %", date).unwrap_err().to_string(),
1987    ///     "strftime formatting failed: invalid format string, \
1988    ///      expected byte after `%`, but found end of format string",
1989    /// );
1990    /// ```
1991    #[inline]
1992    pub fn strftime<'f, F: 'f + ?Sized + AsRef<[u8]>>(
1993        &self,
1994        format: &'f F,
1995    ) -> fmt::strtime::Display<'f> {
1996        fmt::strtime::Display { fmt: format.as_ref(), tm: (*self).into() }
1997    }
1998}
1999
2000/// Internal APIs.
2001impl Date {
2002    #[inline]
2003    pub(crate) const fn until_days(self, other: Date) -> i32 {
2004        self.inner.until(other.inner)
2005    }
2006
2007    #[cfg_attr(feature = "perf-inline", inline(always))]
2008    pub(crate) fn to_unix_epoch_day(self) -> jcore::civil::UnixEpochDay {
2009        self.inner.to_unix_epoch_day()
2010    }
2011
2012    #[cfg_attr(feature = "perf-inline", inline(always))]
2013    pub(crate) fn from_unix_epoch_day(
2014        day: jcore::civil::UnixEpochDay,
2015    ) -> Date {
2016        Date::from_jcore(day.to_date())
2017    }
2018
2019    #[inline]
2020    pub(crate) const fn to_jcore(self) -> JDate {
2021        self.inner
2022    }
2023
2024    #[inline]
2025    pub(crate) const fn from_jcore(date: JDate) -> Date {
2026        Date { inner: date }
2027    }
2028}
2029
2030impl Default for Date {
2031    fn default() -> Date {
2032        Date::ZERO
2033    }
2034}
2035
2036impl core::fmt::Debug for Date {
2037    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2038        core::fmt::Display::fmt(self, f)
2039    }
2040}
2041
2042impl core::fmt::Display for Date {
2043    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2044        use crate::fmt::StdFmtWrite;
2045
2046        DEFAULT_DATETIME_PRINTER
2047            .print_date(self, StdFmtWrite(f))
2048            .map_err(|_| core::fmt::Error)
2049    }
2050}
2051
2052impl core::str::FromStr for Date {
2053    type Err = Error;
2054
2055    fn from_str(string: &str) -> Result<Date, Error> {
2056        DEFAULT_DATETIME_PARSER.parse_date(string)
2057    }
2058}
2059
2060impl From<ISOWeekDate> for Date {
2061    #[inline]
2062    fn from(weekdate: ISOWeekDate) -> Date {
2063        Date::from_iso_week_date(weekdate)
2064    }
2065}
2066
2067impl From<DateTime> for Date {
2068    #[inline]
2069    fn from(dt: DateTime) -> Date {
2070        dt.date()
2071    }
2072}
2073
2074impl From<ZonedDateTime> for Date {
2075    #[inline]
2076    fn from(zdt: ZonedDateTime) -> Date {
2077        zdt.datetime().date()
2078    }
2079}
2080
2081impl<'a> From<&'a ZonedDateTime> for Date {
2082    #[inline]
2083    fn from(zdt: &'a ZonedDateTime) -> Date {
2084        zdt.datetime().date()
2085    }
2086}
2087
2088/// Adds a span of time to a date.
2089///
2090/// This uses checked arithmetic and panics on overflow. To handle overflow
2091/// without panics, use [`Date::checked_add`].
2092impl core::ops::Add<Span> for Date {
2093    type Output = Date;
2094
2095    #[inline]
2096    fn add(self, rhs: Span) -> Date {
2097        self.checked_add(rhs).expect("adding span to date overflowed")
2098    }
2099}
2100
2101/// Adds a span of time to a date in place.
2102///
2103/// This uses checked arithmetic and panics on overflow. To handle overflow
2104/// without panics, use [`Date::checked_add`].
2105impl core::ops::AddAssign<Span> for Date {
2106    #[inline]
2107    fn add_assign(&mut self, rhs: Span) {
2108        *self = *self + rhs;
2109    }
2110}
2111
2112/// Subtracts a span of time from a date.
2113///
2114/// This uses checked arithmetic and panics on overflow. To handle overflow
2115/// without panics, use [`Date::checked_sub`].
2116impl core::ops::Sub<Span> for Date {
2117    type Output = Date;
2118
2119    #[inline]
2120    fn sub(self, rhs: Span) -> Date {
2121        self.checked_sub(rhs).expect("subing span to date overflowed")
2122    }
2123}
2124
2125/// Subtracts a span of time from a date in place.
2126///
2127/// This uses checked arithmetic and panics on overflow. To handle overflow
2128/// without panics, use [`Date::checked_sub`].
2129impl core::ops::SubAssign<Span> for Date {
2130    #[inline]
2131    fn sub_assign(&mut self, rhs: Span) {
2132        *self = *self - rhs;
2133    }
2134}
2135
2136/// Computes the span of time between two dates.
2137///
2138/// This will return a negative span when the date being subtracted is greater.
2139///
2140/// Since this uses the default configuration for calculating a span between
2141/// two date (no rounding and largest units is days), this will never panic or
2142/// fail in any way.
2143///
2144/// To configure the largest unit or enable rounding, use [`Date::since`].
2145impl core::ops::Sub for Date {
2146    type Output = Span;
2147
2148    #[inline]
2149    fn sub(self, rhs: Date) -> Span {
2150        self.since(rhs).expect("since never fails when given Date")
2151    }
2152}
2153
2154/// Adds a signed duration of time to a date.
2155///
2156/// This uses checked arithmetic and panics on overflow. To handle overflow
2157/// without panics, use [`Date::checked_add`].
2158impl core::ops::Add<SignedDuration> for Date {
2159    type Output = Date;
2160
2161    #[inline]
2162    fn add(self, rhs: SignedDuration) -> Date {
2163        self.checked_add(rhs)
2164            .expect("adding signed duration to date overflowed")
2165    }
2166}
2167
2168/// Adds a signed duration of time to a date in place.
2169///
2170/// This uses checked arithmetic and panics on overflow. To handle overflow
2171/// without panics, use [`Date::checked_add`].
2172impl core::ops::AddAssign<SignedDuration> for Date {
2173    #[inline]
2174    fn add_assign(&mut self, rhs: SignedDuration) {
2175        *self = *self + rhs;
2176    }
2177}
2178
2179/// Subtracts a signed duration of time from a date.
2180///
2181/// This uses checked arithmetic and panics on overflow. To handle overflow
2182/// without panics, use [`Date::checked_sub`].
2183impl core::ops::Sub<SignedDuration> for Date {
2184    type Output = Date;
2185
2186    #[inline]
2187    fn sub(self, rhs: SignedDuration) -> Date {
2188        self.checked_sub(rhs)
2189            .expect("subing signed duration to date overflowed")
2190    }
2191}
2192
2193/// Subtracts a signed duration of time from a date in place.
2194///
2195/// This uses checked arithmetic and panics on overflow. To handle overflow
2196/// without panics, use [`Date::checked_sub`].
2197impl core::ops::SubAssign<SignedDuration> for Date {
2198    #[inline]
2199    fn sub_assign(&mut self, rhs: SignedDuration) {
2200        *self = *self - rhs;
2201    }
2202}
2203
2204/// Adds an unsigned duration of time to a date.
2205///
2206/// This uses checked arithmetic and panics on overflow. To handle overflow
2207/// without panics, use [`Date::checked_add`].
2208impl core::ops::Add<UnsignedDuration> for Date {
2209    type Output = Date;
2210
2211    #[inline]
2212    fn add(self, rhs: UnsignedDuration) -> Date {
2213        self.checked_add(rhs)
2214            .expect("adding unsigned duration to date overflowed")
2215    }
2216}
2217
2218/// Adds an unsigned duration of time to a date in place.
2219///
2220/// This uses checked arithmetic and panics on overflow. To handle overflow
2221/// without panics, use [`Date::checked_add`].
2222impl core::ops::AddAssign<UnsignedDuration> for Date {
2223    #[inline]
2224    fn add_assign(&mut self, rhs: UnsignedDuration) {
2225        *self = *self + rhs;
2226    }
2227}
2228
2229/// Subtracts an unsigned duration of time from a date.
2230///
2231/// This uses checked arithmetic and panics on overflow. To handle overflow
2232/// without panics, use [`Date::checked_sub`].
2233impl core::ops::Sub<UnsignedDuration> for Date {
2234    type Output = Date;
2235
2236    #[inline]
2237    fn sub(self, rhs: UnsignedDuration) -> Date {
2238        self.checked_sub(rhs)
2239            .expect("subing unsigned duration to date overflowed")
2240    }
2241}
2242
2243/// Subtracts an unsigned duration of time from a date in place.
2244///
2245/// This uses checked arithmetic and panics on overflow. To handle overflow
2246/// without panics, use [`Date::checked_sub`].
2247impl core::ops::SubAssign<UnsignedDuration> for Date {
2248    #[inline]
2249    fn sub_assign(&mut self, rhs: UnsignedDuration) {
2250        *self = *self - rhs;
2251    }
2252}
2253
2254#[cfg(feature = "defmt")]
2255impl defmt::Format for Date {
2256    fn format(&self, f: defmt::Formatter) {
2257        use crate::fmt::DefmtWrite;
2258
2259        defmt::unwrap!(
2260            DEFAULT_DATETIME_PRINTER.print_date(self, DefmtWrite(f))
2261        );
2262    }
2263}
2264
2265#[cfg(feature = "serde")]
2266impl serde_core::Serialize for Date {
2267    #[inline]
2268    fn serialize<S: serde_core::Serializer>(
2269        &self,
2270        serializer: S,
2271    ) -> Result<S::Ok, S::Error> {
2272        serializer.collect_str(self)
2273    }
2274}
2275
2276#[cfg(feature = "serde")]
2277impl<'de> serde_core::Deserialize<'de> for Date {
2278    #[inline]
2279    fn deserialize<D: serde_core::Deserializer<'de>>(
2280        deserializer: D,
2281    ) -> Result<Date, D::Error> {
2282        use serde_core::de;
2283
2284        struct DateVisitor;
2285
2286        impl<'de> de::Visitor<'de> for DateVisitor {
2287            type Value = Date;
2288
2289            fn expecting(
2290                &self,
2291                f: &mut core::fmt::Formatter,
2292            ) -> core::fmt::Result {
2293                f.write_str("a date string")
2294            }
2295
2296            #[inline]
2297            fn visit_bytes<E: de::Error>(
2298                self,
2299                value: &[u8],
2300            ) -> Result<Date, E> {
2301                DEFAULT_DATETIME_PARSER
2302                    .parse_date(value)
2303                    .map_err(de::Error::custom)
2304            }
2305
2306            #[inline]
2307            fn visit_str<E: de::Error>(self, value: &str) -> Result<Date, E> {
2308                self.visit_bytes(value.as_bytes())
2309            }
2310        }
2311
2312        deserializer.deserialize_str(DateVisitor)
2313    }
2314}
2315
2316#[cfg(test)]
2317impl quickcheck::Arbitrary for Date {
2318    fn arbitrary(g: &mut quickcheck::Gen) -> Date {
2319        let year = b::Year::arbitrary(g);
2320        let month = b::Month::arbitrary(g);
2321        let day = b::Day::arbitrary(g);
2322        Date::new_constrain(year, month, day).unwrap()
2323    }
2324
2325    fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Date>> {
2326        alloc::boxed::Box::new(
2327            (self.year(), self.month(), self.day()).shrink().filter_map(
2328                |(year, month, day)| {
2329                    Date::new_constrain(year, month, day).ok()
2330                },
2331            ),
2332        )
2333    }
2334}
2335
2336/// An iterator over periodic dates, created by [`Date::series`].
2337///
2338/// It is exhausted when the next value would exceed the limits of a [`Span`]
2339/// or [`Date`] value.
2340///
2341/// This iterator is created by [`Date::series`].
2342#[derive(#[automatically_derived]impl ::core::clone::Clone for DateSeries {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        DateSeries {
            start: ::core::clone::Clone::clone(&self.start),
            period: ::core::clone::Clone::clone(&self.period),
            step: ::core::clone::Clone::clone(&self.step),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for DateSeries {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "DateSeries start period step", &self.start, &self.period,
            &&self.step)
    }
}Debug)]
2343pub struct DateSeries {
2344    start: Date,
2345    period: Span,
2346    step: i64,
2347}
2348
2349impl Iterator for DateSeries {
2350    type Item = Date;
2351
2352    #[inline]
2353    fn next(&mut self) -> Option<Date> {
2354        let span = self.period.checked_mul(self.step).ok()?;
2355        self.step = self.step.checked_add(1)?;
2356        let date = self.start.checked_add(span).ok()?;
2357        Some(date)
2358    }
2359}
2360
2361impl core::iter::FusedIterator for DateSeries {}
2362
2363/// Options for [`Date::checked_add`] and [`Date::checked_sub`].
2364///
2365/// This type provides a way to ergonomically add one of a few different
2366/// duration types to a [`Date`].
2367///
2368/// The main way to construct values of this type is with its `From` trait
2369/// implementations:
2370///
2371/// * `From<Span> for DateArithmetic` adds (or subtracts) the given span to the
2372/// receiver date.
2373/// * `From<SignedDuration> for DateArithmetic` adds (or subtracts)
2374/// the given signed duration to the receiver date.
2375/// * `From<std::time::Duration> for DateArithmetic` adds (or subtracts)
2376/// the given unsigned duration to the receiver date.
2377///
2378/// # Example
2379///
2380/// ```
2381/// use std::time::Duration;
2382///
2383/// use jiff::{civil::date, SignedDuration, ToSpan};
2384///
2385/// let d = date(2024, 2, 29);
2386/// assert_eq!(d.checked_add(1.year())?, date(2025, 2, 28));
2387/// assert_eq!(d.checked_add(SignedDuration::from_hours(24))?, date(2024, 3, 1));
2388/// assert_eq!(d.checked_add(Duration::from_secs(24 * 60 * 60))?, date(2024, 3, 1));
2389///
2390/// # Ok::<(), Box<dyn std::error::Error>>(())
2391/// ```
2392#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DateArithmetic {
}
#[automatically_derived]impl ::core::clone::Clone for DateArithmetic {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Duration>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for DateArithmetic { }Copy, #[automatically_derived]impl ::core::fmt::Debug for DateArithmetic {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "DateArithmetic duration", &&self.duration)
    }
}Debug)]
2393pub struct DateArithmetic {
2394    duration: Duration,
2395}
2396
2397impl DateArithmetic {
2398    #[inline]
2399    fn checked_add(self, date: Date) -> Result<Date, Error> {
2400        match self.duration.to_signed()? {
2401            SDuration::Span(span) => date.checked_add_span(span),
2402            SDuration::Absolute(sdur) => date.checked_add_duration(sdur),
2403        }
2404    }
2405
2406    #[inline]
2407    fn checked_neg(self) -> Result<DateArithmetic, Error> {
2408        let duration = self.duration.checked_neg()?;
2409        Ok(DateArithmetic { duration })
2410    }
2411
2412    #[inline]
2413    fn is_negative(&self) -> bool {
2414        self.duration.is_negative()
2415    }
2416}
2417
2418impl From<Span> for DateArithmetic {
2419    fn from(span: Span) -> DateArithmetic {
2420        let duration = Duration::from(span);
2421        DateArithmetic { duration }
2422    }
2423}
2424
2425impl From<SignedDuration> for DateArithmetic {
2426    fn from(sdur: SignedDuration) -> DateArithmetic {
2427        let duration = Duration::from(sdur);
2428        DateArithmetic { duration }
2429    }
2430}
2431
2432impl From<UnsignedDuration> for DateArithmetic {
2433    fn from(udur: UnsignedDuration) -> DateArithmetic {
2434        let duration = Duration::from(udur);
2435        DateArithmetic { duration }
2436    }
2437}
2438
2439impl<'a> From<&'a Span> for DateArithmetic {
2440    fn from(span: &'a Span) -> DateArithmetic {
2441        DateArithmetic::from(*span)
2442    }
2443}
2444
2445impl<'a> From<&'a SignedDuration> for DateArithmetic {
2446    fn from(sdur: &'a SignedDuration) -> DateArithmetic {
2447        DateArithmetic::from(*sdur)
2448    }
2449}
2450
2451impl<'a> From<&'a UnsignedDuration> for DateArithmetic {
2452    fn from(udur: &'a UnsignedDuration) -> DateArithmetic {
2453        DateArithmetic::from(*udur)
2454    }
2455}
2456
2457/// Options for [`Date::since`] and [`Date::until`].
2458///
2459/// This type provides a way to configure the calculation of spans between two
2460/// [`Date`] values. In particular, both `Date::since` and `Date::until` accept
2461/// anything that implements `Into<DateDifference>`. There are a few key trait
2462/// implementations that make this convenient:
2463///
2464/// * `From<Date> for DateDifference` will construct a configuration consisting
2465/// of just the date. So for example, `date1.until(date2)` will return the span
2466/// from `date1` to `date2`.
2467/// * `From<DateTime> for DateDifference` will construct a configuration
2468/// consisting of just the date from the given datetime. So for example,
2469/// `date.since(datetime)` returns the span from `datetime.date()` to `date`.
2470/// * `From<(Unit, Date)>` is a convenient way to specify the largest units
2471/// that should be present on the span returned. By default, the largest units
2472/// are days. Using this trait implementation is equivalent to
2473/// `DateDifference::new(date).largest(unit)`.
2474/// * `From<(Unit, DateTime)>` is like the one above, but with the date from
2475/// the given datetime.
2476///
2477/// One can also provide a `DateDifference` value directly. Doing so is
2478/// necessary to use the rounding features of calculating a span. For example,
2479/// setting the smallest unit (defaults to [`Unit::Day`]), the rounding mode
2480/// (defaults to [`RoundMode::Trunc`]) and the rounding increment (defaults to
2481/// `1`). The defaults are selected such that no rounding occurs.
2482///
2483/// Rounding a span as part of calculating it is provided as a convenience.
2484/// Callers may choose to round the span as a distinct step via
2485/// [`Span::round`], but callers may need to provide a reference date
2486/// for rounding larger units. By coupling rounding with routines like
2487/// [`Date::since`], the reference date can be set automatically based on
2488/// the input to `Date::since`.
2489///
2490/// # Example
2491///
2492/// This example shows how to round a span between two date to the nearest
2493/// year, with ties breaking away from zero.
2494///
2495/// ```
2496/// use jiff::{civil::{Date, DateDifference}, RoundMode, ToSpan, Unit};
2497///
2498/// let d1 = "2024-03-15".parse::<Date>()?;
2499/// let d2 = "2030-09-13".parse::<Date>()?;
2500/// let span = d1.until(
2501///     DateDifference::new(d2)
2502///         .smallest(Unit::Year)
2503///         .mode(RoundMode::HalfExpand),
2504/// )?;
2505/// assert_eq!(span, 6.years().fieldwise());
2506///
2507/// // If the span were one day longer, it would round up to 7 years.
2508/// let d2 = "2030-09-14".parse::<Date>()?;
2509/// let span = d1.until(
2510///     DateDifference::new(d2)
2511///         .smallest(Unit::Year)
2512///         .mode(RoundMode::HalfExpand),
2513/// )?;
2514/// assert_eq!(span, 7.years().fieldwise());
2515///
2516/// # Ok::<(), Box<dyn std::error::Error>>(())
2517/// ```
2518#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DateDifference {
}
#[automatically_derived]impl ::core::clone::Clone for DateDifference {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Date>;
        let _: ::core::clone::AssertParamIsClone<SpanRound<'static>>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for DateDifference { }Copy, #[automatically_derived]impl ::core::fmt::Debug for DateDifference {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "DateDifference date round", &self.date, &&self.round)
    }
}Debug)]
2519pub struct DateDifference {
2520    date: Date,
2521    round: SpanRound<'static>,
2522}
2523
2524impl DateDifference {
2525    /// Create a new default configuration for computing the span between
2526    /// the given date and some other date (specified as the receiver in
2527    /// [`Date::since`] or [`Date::until`]).
2528    #[inline]
2529    pub fn new(date: Date) -> DateDifference {
2530        // We use truncation rounding by default since it seems that's
2531        // what is generally expected when computing the difference between
2532        // datetimes.
2533        //
2534        // See: https://github.com/tc39/proposal-temporal/issues/1122
2535        let round =
2536            SpanRound::new().mode(RoundMode::Trunc).smallest(Unit::Day);
2537        DateDifference { date, round }
2538    }
2539
2540    /// Set the smallest units allowed in the span returned.
2541    ///
2542    /// When a largest unit is not specified, then the largest unit is
2543    /// automatically set to be equal to the smallest unit.
2544    ///
2545    /// This defaults to `Unit::Day`.
2546    ///
2547    /// # Errors
2548    ///
2549    /// The smallest units must be no greater than the largest units. If this
2550    /// is violated, then computing a span with this configuration will result
2551    /// in an error.
2552    ///
2553    /// The unit set must also be a calendar unit. Using a time unit will
2554    /// result in an error.
2555    ///
2556    /// # Example
2557    ///
2558    /// This shows how to round a span between two date to the nearest
2559    /// number of weeks.
2560    ///
2561    /// ```
2562    /// use jiff::{civil::{Date, DateDifference}, RoundMode, ToSpan, Unit};
2563    ///
2564    /// let d1 = "2024-03-15".parse::<Date>()?;
2565    /// let d2 = "2030-11-22".parse::<Date>()?;
2566    /// let span = d1.until(
2567    ///     DateDifference::new(d2)
2568    ///         .smallest(Unit::Week)
2569    ///         .largest(Unit::Week)
2570    ///         .mode(RoundMode::HalfExpand),
2571    /// )?;
2572    /// assert_eq!(span, 349.weeks().fieldwise());
2573    ///
2574    /// # Ok::<(), Box<dyn std::error::Error>>(())
2575    /// ```
2576    #[inline]
2577    pub fn smallest(self, unit: Unit) -> DateDifference {
2578        DateDifference { round: self.round.smallest(unit), ..self }
2579    }
2580
2581    /// Set the largest units allowed in the span returned.
2582    ///
2583    /// When a largest unit is not specified, then the largest unit is
2584    /// automatically set to be equal to the smallest unit or `Unit::Day`,
2585    /// whichever is greater. Otherwise, when the largest unit is not
2586    /// specified, it is set to days.
2587    ///
2588    /// Once a largest unit is set, there is no way to change this rounding
2589    /// configuration back to using the "automatic" default. Instead, callers
2590    /// must create a new configuration.
2591    ///
2592    /// # Errors
2593    ///
2594    /// The largest units, when set, must be at least as big as the smallest
2595    /// units (which defaults to [`Unit::Day`]). If this is violated, then
2596    /// computing a span with this configuration will result in an error.
2597    ///
2598    /// The unit set must also be a calendar unit. Using a time unit will
2599    /// result in an error.
2600    ///
2601    /// # Example
2602    ///
2603    /// This shows how to round a span between two date to units no
2604    /// bigger than months.
2605    ///
2606    /// ```
2607    /// use jiff::{civil::{Date, DateDifference}, ToSpan, Unit};
2608    ///
2609    /// let d1 = "2024-03-15".parse::<Date>()?;
2610    /// let d2 = "2030-11-22".parse::<Date>()?;
2611    /// let span = d1.until(
2612    ///     DateDifference::new(d2).largest(Unit::Month),
2613    /// )?;
2614    /// assert_eq!(span, 80.months().days(7).fieldwise());
2615    ///
2616    /// # Ok::<(), Box<dyn std::error::Error>>(())
2617    /// ```
2618    #[inline]
2619    pub fn largest(self, unit: Unit) -> DateDifference {
2620        DateDifference { round: self.round.largest(unit), ..self }
2621    }
2622
2623    /// Set the rounding mode.
2624    ///
2625    /// This defaults to [`RoundMode::Trunc`] since it's plausible that
2626    /// rounding "up" in the context of computing the span between two date
2627    /// could be surprising in a number of cases. The [`RoundMode::HalfExpand`]
2628    /// mode corresponds to typical rounding you might have learned about in
2629    /// school. But a variety of other rounding modes exist.
2630    ///
2631    /// # Example
2632    ///
2633    /// This shows how to always round "up" towards positive infinity.
2634    ///
2635    /// ```
2636    /// use jiff::{civil::{Date, DateDifference}, RoundMode, ToSpan, Unit};
2637    ///
2638    /// let d1 = "2024-01-15".parse::<Date>()?;
2639    /// let d2 = "2024-08-16".parse::<Date>()?;
2640    /// let span = d1.until(
2641    ///     DateDifference::new(d2)
2642    ///         .smallest(Unit::Month)
2643    ///         .mode(RoundMode::Ceil),
2644    /// )?;
2645    /// // Only 7 months and 1 day elapsed, but we asked to always round up!
2646    /// assert_eq!(span, 8.months().fieldwise());
2647    ///
2648    /// // Since `Ceil` always rounds toward positive infinity, the behavior
2649    /// // flips for a negative span.
2650    /// let span = d1.since(
2651    ///     DateDifference::new(d2)
2652    ///         .smallest(Unit::Month)
2653    ///         .mode(RoundMode::Ceil),
2654    /// )?;
2655    /// assert_eq!(span, -7.months().fieldwise());
2656    ///
2657    /// # Ok::<(), Box<dyn std::error::Error>>(())
2658    /// ```
2659    #[inline]
2660    pub fn mode(self, mode: RoundMode) -> DateDifference {
2661        DateDifference { round: self.round.mode(mode), ..self }
2662    }
2663
2664    /// Set the rounding increment for the smallest unit.
2665    ///
2666    /// The default value is `1`. Other values permit rounding the smallest
2667    /// unit to the nearest integer increment specified. For example, if the
2668    /// smallest unit is set to [`Unit::Month`], then a rounding increment of
2669    /// `2` would result in rounding in increments of every other month.
2670    ///
2671    /// # Errors
2672    ///
2673    /// The increment must be greater than zero and less than or equal to
2674    /// `1_000_000_000`.
2675    ///
2676    /// The error will occur when computing the span, and not when setting
2677    /// the increment here.
2678    ///
2679    /// # Example
2680    ///
2681    /// This shows how to round the span between two date to the nearest even
2682    /// month.
2683    ///
2684    /// ```
2685    /// use jiff::{civil::{Date, DateDifference}, RoundMode, ToSpan, Unit};
2686    ///
2687    /// let d1 = "2024-01-15".parse::<Date>()?;
2688    /// let d2 = "2024-08-15".parse::<Date>()?;
2689    /// let span = d1.until(
2690    ///     DateDifference::new(d2)
2691    ///         .smallest(Unit::Month)
2692    ///         .increment(2)
2693    ///         .mode(RoundMode::HalfExpand),
2694    /// )?;
2695    /// assert_eq!(span, 8.months().fieldwise());
2696    ///
2697    /// // If our second date was just one day less, rounding would truncate
2698    /// // down to 6 months!
2699    /// let d2 = "2024-08-14".parse::<Date>()?;
2700    /// let span = d1.until(
2701    ///     DateDifference::new(d2)
2702    ///         .smallest(Unit::Month)
2703    ///         .increment(2)
2704    ///         .mode(RoundMode::HalfExpand),
2705    /// )?;
2706    /// assert_eq!(span, 6.months().fieldwise());
2707    ///
2708    /// # Ok::<(), Box<dyn std::error::Error>>(())
2709    /// ```
2710    #[inline]
2711    pub fn increment(self, increment: i64) -> DateDifference {
2712        DateDifference { round: self.round.increment(increment), ..self }
2713    }
2714
2715    /// Returns true if and only if this configuration could change the span
2716    /// via rounding.
2717    #[inline]
2718    fn rounding_may_change_span(&self) -> bool {
2719        self.round.rounding_calendar_only_may_change_span()
2720    }
2721
2722    /// Returns the span of time since `d1` to the date in this configuration.
2723    /// The biggest units allowed are determined by the `smallest` and
2724    /// `largest` settings, but defaults to `Unit::Day`.
2725    #[inline]
2726    fn since_with_largest_unit(&self, d1: Date) -> Result<Span, Error> {
2727        // N.B. A logical (but inefficient yet easier to understand)
2728        // description of the behavior here can be found in the Temporal spec:
2729        // https://tc39.es/proposal-temporal/#sec-temporal-calendardateuntil
2730        //
2731        // Immense discussion discussing and justifying this behavior:
2732        // https://github.com/tc39/proposal-temporal/issues/2535
2733
2734        let smallest = self.round.get_smallest();
2735        if smallest < Unit::Day {
2736            return Err(Error::from(UnitConfigError::CivilDate {
2737                given: smallest,
2738            }));
2739        }
2740
2741        let largest = self.round.get_largest().unwrap_or(smallest);
2742        if largest < Unit::Day {
2743            return Err(Error::from(UnitConfigError::CivilDate {
2744                given: largest,
2745            }));
2746        }
2747
2748        let d2 = self.date;
2749        if d1 == d2 {
2750            return Ok(Span::new());
2751        }
2752        if largest <= Unit::Week {
2753            let mut weeks: i32 = 0;
2754            let mut days = d1.until_days(d2);
2755            if largest == Unit::Week {
2756                weeks = days / 7;
2757                days %= 7;
2758            }
2759            return Ok(Span::new().weeks(weeks).days(days));
2760        }
2761
2762        let year1 = d1.year();
2763        let month1 = d1.month();
2764        let day1 = d1.day();
2765        let mut year2 = d2.year();
2766        let mut month2 = d2.month();
2767        let day2 = d2.day();
2768
2769        let mut years = year2 - year1;
2770        let mut months = i32::from(month2 - month1);
2771        let mut days = i32::from(day2 - day1);
2772        if years != 0 || months != 0 {
2773            let sign = if years != 0 {
2774                Sign::from(years)
2775            } else {
2776                Sign::from(months)
2777            };
2778            let mut days_in_month2 = d2.days_in_month();
2779            let mut day_correct = 0;
2780            if Sign::from(days) == -sign {
2781                // Justifying this operation as infallible is quite tricky.
2782                // It can only fail in two cases: year2=9999, month2=12 and
2783                // sign=Negative or year2=-9999, month2=1 and sign=Positive. In
2784                // both of those cases, year will overflow its boundaries.
2785                //
2786                // However, neither case is possible. Namely, whenever
2787                // sign=Negative, it follows that either `year1 > year2` or
2788                // `month1 > month2`. But there are no such values of `year1`
2789                // or `month1` that satisfy `year1 > 9999 or month1 > 12`
2790                // because `9999` is the maximum legal year value.
2791                //
2792                // A similar argument follows for sign=Positive and
2793                // `year2=-9999` and `month2=1`. Therefore, this `unwrap()` is
2794                // okay.
2795                let (y, m) = month_add_one(year2, month2, -sign).unwrap();
2796                year2 = y;
2797                month2 = m;
2798
2799                years = year2 - year1;
2800                months = i32::from(month2 - month1);
2801                let original_days_in_month1 = days_in_month2;
2802                days_in_month2 = jcore::civil::days_in_month(year2, month2);
2803                day_correct = if sign.is_negative() {
2804                    -original_days_in_month1
2805                } else {
2806                    days_in_month2
2807                };
2808            }
2809
2810            let day0_trunc = i32::from(day1.min(days_in_month2));
2811            days = i32::from(day2) - day0_trunc + i32::from(day_correct);
2812
2813            if years != 0 {
2814                months = i32::from(month2 - month1);
2815                if Sign::from(months) == -sign {
2816                    let month_correct = sign * 12;
2817                    year2 -= sign.as_i16();
2818                    years = year2 - year1;
2819
2820                    months = i32::from(month2 - month1) + month_correct;
2821                }
2822            }
2823        }
2824        if largest == Unit::Month && years != 0 {
2825            months =
2826                b::SpanMonths::checked_add(months, i32::from(years) * 12)?;
2827            years = 0;
2828        }
2829        Ok(Span::new().years(years).months(months).days(days))
2830    }
2831}
2832
2833impl From<Date> for DateDifference {
2834    #[inline]
2835    fn from(date: Date) -> DateDifference {
2836        DateDifference::new(date)
2837    }
2838}
2839
2840impl From<DateTime> for DateDifference {
2841    #[inline]
2842    fn from(dt: DateTime) -> DateDifference {
2843        DateDifference::from(Date::from(dt))
2844    }
2845}
2846
2847impl From<ZonedDateTime> for DateDifference {
2848    #[inline]
2849    fn from(zdt: ZonedDateTime) -> DateDifference {
2850        DateDifference::from(Date::from(zdt))
2851    }
2852}
2853
2854impl<'a> From<&'a ZonedDateTime> for DateDifference {
2855    #[inline]
2856    fn from(zdt: &'a ZonedDateTime) -> DateDifference {
2857        DateDifference::from(zdt.datetime())
2858    }
2859}
2860
2861impl From<(Unit, Date)> for DateDifference {
2862    #[inline]
2863    fn from((largest, date): (Unit, Date)) -> DateDifference {
2864        DateDifference::from(date).largest(largest)
2865    }
2866}
2867
2868impl From<(Unit, DateTime)> for DateDifference {
2869    #[inline]
2870    fn from((largest, dt): (Unit, DateTime)) -> DateDifference {
2871        DateDifference::from((largest, Date::from(dt)))
2872    }
2873}
2874
2875impl From<(Unit, ZonedDateTime)> for DateDifference {
2876    #[inline]
2877    fn from((largest, zdt): (Unit, ZonedDateTime)) -> DateDifference {
2878        DateDifference::from((largest, Date::from(zdt)))
2879    }
2880}
2881
2882impl<'a> From<(Unit, &'a ZonedDateTime)> for DateDifference {
2883    #[inline]
2884    fn from((largest, zdt): (Unit, &'a ZonedDateTime)) -> DateDifference {
2885        DateDifference::from((largest, zdt.datetime()))
2886    }
2887}
2888
2889/// A builder for setting the fields on a [`Date`].
2890///
2891/// This builder is constructed via [`Date::with`].
2892///
2893/// # Example
2894///
2895/// The builder ensures one can chain together the individual components
2896/// of a date without it failing at an intermediate step. For example,
2897/// if you had a date of `2024-10-31` and wanted to change both the day
2898/// and the month, and each setting was validated independent of the other,
2899/// you would need to be careful to set the day first and then the month.
2900/// In some cases, you would need to set the month first and then the day!
2901///
2902/// But with the builder, you can set values in any order:
2903///
2904/// ```
2905/// use jiff::civil::date;
2906///
2907/// let d1 = date(2024, 10, 31);
2908/// let d2 = d1.with().month(11).day(30).build()?;
2909/// assert_eq!(d2, date(2024, 11, 30));
2910///
2911/// let d1 = date(2024, 4, 30);
2912/// let d2 = d1.with().day(31).month(7).build()?;
2913/// assert_eq!(d2, date(2024, 7, 31));
2914///
2915/// # Ok::<(), Box<dyn std::error::Error>>(())
2916/// ```
2917#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DateWith {
}
#[automatically_derived]impl ::core::clone::Clone for DateWith {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Date>;
        let _: ::core::clone::AssertParamIsClone<Option<DateWithYear>>;
        let _: ::core::clone::AssertParamIsClone<Option<i8>>;
        let _: ::core::clone::AssertParamIsClone<Option<DateWithDay>>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for DateWith { }Copy, #[automatically_derived]impl ::core::fmt::Debug for DateWith {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "DateWith original year month day", &self.original, &self.year,
            &self.month, &&self.day)
    }
}Debug)]
2918pub struct DateWith {
2919    original: Date,
2920    year: Option<DateWithYear>,
2921    month: Option<i8>,
2922    day: Option<DateWithDay>,
2923}
2924
2925impl DateWith {
2926    #[inline]
2927    fn new(original: Date) -> DateWith {
2928        DateWith { original, year: None, month: None, day: None }
2929    }
2930
2931    /// Create a new `Date` from the fields set on this configuration.
2932    ///
2933    /// An error occurs when the fields combine to an invalid date.
2934    ///
2935    /// For any fields not set on this configuration, the values are taken from
2936    /// the [`Date`] that originally created this configuration. When no values
2937    /// are set, this routine is guaranteed to succeed and will always return
2938    /// the original date without modification.
2939    ///
2940    /// # Example
2941    ///
2942    /// This creates a date corresponding to the last day in the year:
2943    ///
2944    /// ```
2945    /// use jiff::civil::date;
2946    ///
2947    /// assert_eq!(
2948    ///     date(2023, 1, 1).with().day_of_year_no_leap(365).build()?,
2949    ///     date(2023, 12, 31),
2950    /// );
2951    /// // It also works with leap years for the same input:
2952    /// assert_eq!(
2953    ///     date(2024, 1, 1).with().day_of_year_no_leap(365).build()?,
2954    ///     date(2024, 12, 31),
2955    /// );
2956    ///
2957    /// # Ok::<(), Box<dyn std::error::Error>>(())
2958    /// ```
2959    ///
2960    /// # Example: error for invalid date
2961    ///
2962    /// If the fields combine to form an invalid date, then an error is
2963    /// returned:
2964    ///
2965    /// ```
2966    /// use jiff::civil::date;
2967    ///
2968    /// let d = date(2024, 11, 30);
2969    /// assert!(d.with().day(31).build().is_err());
2970    ///
2971    /// let d = date(2024, 2, 29);
2972    /// assert!(d.with().year(2023).build().is_err());
2973    /// ```
2974    #[inline]
2975    pub fn build(self) -> Result<Date, Error> {
2976        let year = match self.year {
2977            None => self.original.year(),
2978            Some(DateWithYear::Jiff(year)) => b::Year::check(year)?,
2979            Some(DateWithYear::EraYear(year, Era::CE)) => {
2980                b::YearCE::check(year)?
2981            }
2982            Some(DateWithYear::EraYear(year, Era::BCE)) => {
2983                let year_bce = b::YearBCE::check(year)?;
2984                -year_bce + 1
2985            }
2986        };
2987        let month = match self.month {
2988            None => self.original.month(),
2989            Some(month) => b::Month::check(month)?,
2990        };
2991        let day = match self.day {
2992            None => self.original.day(),
2993            Some(DateWithDay::OfMonth(day)) => b::Day::check(day)?,
2994            Some(DateWithDay::OfYear(day)) => {
2995                let jdate = JDate::from_day_of_year(year, day)
2996                    .map_err(Error::jcore_range)?;
2997                return Ok(Date::from_jcore(jdate));
2998            }
2999            Some(DateWithDay::OfYearNoLeap(day)) => {
3000                let jdate = JDate::from_day_of_year_no_leap(year, day)
3001                    .map_err(Error::jcore_range)?;
3002                return Ok(Date::from_jcore(jdate));
3003            }
3004        };
3005        Date::new(year, month, day)
3006    }
3007
3008    /// Set the year field on a [`Date`].
3009    ///
3010    /// One can access this value via [`Date::year`].
3011    ///
3012    /// This overrides any previous year settings.
3013    ///
3014    /// # Errors
3015    ///
3016    /// This returns an error when [`DateWith::build`] is called if the given
3017    /// year is outside the range `-9999..=9999`. This can also return an error
3018    /// if the resulting date is otherwise invalid.
3019    ///
3020    /// # Example
3021    ///
3022    /// This shows how to create a new date with a different year:
3023    ///
3024    /// ```
3025    /// use jiff::civil::date;
3026    ///
3027    /// let d1 = date(2005, 11, 5);
3028    /// assert_eq!(d1.year(), 2005);
3029    /// let d2 = d1.with().year(2007).build()?;
3030    /// assert_eq!(d2.year(), 2007);
3031    ///
3032    /// # Ok::<(), Box<dyn std::error::Error>>(())
3033    /// ```
3034    ///
3035    /// # Example: only changing the year can fail
3036    ///
3037    /// For example, while `2024-02-29` is valid, `2023-02-29` is not:
3038    ///
3039    /// ```
3040    /// use jiff::civil::date;
3041    ///
3042    /// let d1 = date(2024, 2, 29);
3043    /// assert!(d1.with().year(2023).build().is_err());
3044    /// ```
3045    #[inline]
3046    pub fn year(self, year: i16) -> DateWith {
3047        DateWith { year: Some(DateWithYear::Jiff(year)), ..self }
3048    }
3049
3050    /// Set year of a date via its era and its non-negative numeric component.
3051    ///
3052    /// One can access this value via [`Date::era_year`].
3053    ///
3054    /// # Errors
3055    ///
3056    /// This returns an error when [`DateWith::build`] is called if the year is
3057    /// outside the range for the era specified. For [`Era::BCE`], the range is
3058    /// `1..=10000`. For [`Era::CE`], the range is `1..=9999`.
3059    ///
3060    /// # Example
3061    ///
3062    /// This shows that `CE` years are equivalent to the years used by this
3063    /// crate:
3064    ///
3065    /// ```
3066    /// use jiff::civil::{Era, date};
3067    ///
3068    /// let d1 = date(2005, 11, 5);
3069    /// assert_eq!(d1.year(), 2005);
3070    /// let d2 = d1.with().era_year(2007, Era::CE).build()?;
3071    /// assert_eq!(d2.year(), 2007);
3072    ///
3073    /// // CE years are always positive and can be at most 9999:
3074    /// assert!(d1.with().era_year(-5, Era::CE).build().is_err());
3075    /// assert!(d1.with().era_year(10_000, Era::CE).build().is_err());
3076    ///
3077    /// # Ok::<(), Box<dyn std::error::Error>>(())
3078    /// ```
3079    ///
3080    /// But `BCE` years always correspond to years less than or equal to `0`
3081    /// in this crate:
3082    ///
3083    /// ```
3084    /// use jiff::civil::{Era, date};
3085    ///
3086    /// let d1 = date(-27, 7, 1);
3087    /// assert_eq!(d1.year(), -27);
3088    /// assert_eq!(d1.era_year(), (28, Era::BCE));
3089    ///
3090    /// let d2 = d1.with().era_year(509, Era::BCE).build()?;
3091    /// assert_eq!(d2.year(), -508);
3092    /// assert_eq!(d2.era_year(), (509, Era::BCE));
3093    ///
3094    /// let d2 = d1.with().era_year(10_000, Era::BCE).build()?;
3095    /// assert_eq!(d2.year(), -9_999);
3096    /// assert_eq!(d2.era_year(), (10_000, Era::BCE));
3097    ///
3098    /// // BCE years are always positive and can be at most 10000:
3099    /// assert!(d1.with().era_year(-5, Era::BCE).build().is_err());
3100    /// assert!(d1.with().era_year(10_001, Era::BCE).build().is_err());
3101    ///
3102    /// # Ok::<(), Box<dyn std::error::Error>>(())
3103    /// ```
3104    ///
3105    /// # Example: overrides `DateWith::year`
3106    ///
3107    /// Setting this option will override any previous `DateWith::year`
3108    /// option:
3109    ///
3110    /// ```
3111    /// use jiff::civil::{Era, date};
3112    ///
3113    /// let d1 = date(2024, 7, 2);
3114    /// let d2 = d1.with().year(2000).era_year(1900, Era::CE).build()?;
3115    /// assert_eq!(d2, date(1900, 7, 2));
3116    ///
3117    /// # Ok::<(), Box<dyn std::error::Error>>(())
3118    /// ```
3119    ///
3120    /// Similarly, `DateWith::year` will override any previous call to
3121    /// `DateWith::era_year`:
3122    ///
3123    /// ```
3124    /// use jiff::civil::{Era, date};
3125    ///
3126    /// let d1 = date(2024, 7, 2);
3127    /// let d2 = d1.with().era_year(1900, Era::CE).year(2000).build()?;
3128    /// assert_eq!(d2, date(2000, 7, 2));
3129    ///
3130    /// # Ok::<(), Box<dyn std::error::Error>>(())
3131    /// ```
3132    #[inline]
3133    pub fn era_year(self, year: i16, era: Era) -> DateWith {
3134        DateWith { year: Some(DateWithYear::EraYear(year, era)), ..self }
3135    }
3136
3137    /// Set the month field on a [`Date`].
3138    ///
3139    /// One can access this value via [`Date::month`].
3140    ///
3141    /// This overrides any previous month settings.
3142    ///
3143    /// # Errors
3144    ///
3145    /// This returns an error when [`DateWith::build`] is called if the given
3146    /// month is outside the range `1..=12`. This can also return an error if
3147    /// the resulting date is otherwise invalid.
3148    ///
3149    /// # Example
3150    ///
3151    /// This shows how to create a new date with a different month:
3152    ///
3153    /// ```
3154    /// use jiff::civil::date;
3155    ///
3156    /// let d1 = date(2005, 11, 5);
3157    /// assert_eq!(d1.month(), 11);
3158    /// let d2 = d1.with().month(6).build()?;
3159    /// assert_eq!(d2.month(), 6);
3160    ///
3161    /// # Ok::<(), Box<dyn std::error::Error>>(())
3162    /// ```
3163    ///
3164    /// # Example: only changing the month can fail
3165    ///
3166    /// For example, while `2024-10-31` is valid, `2024-11-31` is not:
3167    ///
3168    /// ```
3169    /// use jiff::civil::date;
3170    ///
3171    /// let d = date(2024, 10, 31);
3172    /// assert!(d.with().month(11).build().is_err());
3173    /// ```
3174    #[inline]
3175    pub fn month(self, month: i8) -> DateWith {
3176        DateWith { month: Some(month), ..self }
3177    }
3178
3179    /// Set the day field on a [`Date`].
3180    ///
3181    /// One can access this value via [`Date::day`].
3182    ///
3183    /// This overrides any previous day settings.
3184    ///
3185    /// # Errors
3186    ///
3187    /// This returns an error when [`DateWith::build`] is called if the given
3188    /// given day is outside of allowable days for the corresponding year and
3189    /// month fields.
3190    ///
3191    /// # Example
3192    ///
3193    /// This shows some examples of setting the day, including a leap day:
3194    ///
3195    /// ```
3196    /// use jiff::civil::date;
3197    ///
3198    /// let d1 = date(2024, 2, 5);
3199    /// assert_eq!(d1.day(), 5);
3200    /// let d2 = d1.with().day(10).build()?;
3201    /// assert_eq!(d2.day(), 10);
3202    /// let d3 = d1.with().day(29).build()?;
3203    /// assert_eq!(d3.day(), 29);
3204    ///
3205    /// # Ok::<(), Box<dyn std::error::Error>>(())
3206    /// ```
3207    ///
3208    /// # Example: changing only the day can fail
3209    ///
3210    /// This shows some examples that will fail:
3211    ///
3212    /// ```
3213    /// use jiff::civil::date;
3214    ///
3215    /// let d1 = date(2023, 2, 5);
3216    /// // 2023 is not a leap year
3217    /// assert!(d1.with().day(29).build().is_err());
3218    ///
3219    /// // September has 30 days, not 31.
3220    /// let d1 = date(2023, 9, 5);
3221    /// assert!(d1.with().day(31).build().is_err());
3222    /// ```
3223    #[inline]
3224    pub fn day(self, day: i8) -> DateWith {
3225        DateWith { day: Some(DateWithDay::OfMonth(day)), ..self }
3226    }
3227
3228    /// Set the day field on a [`Date`] via the ordinal number of a day within
3229    /// a year.
3230    ///
3231    /// When used, any settings for month are ignored since the month is
3232    /// determined by the day of the year.
3233    ///
3234    /// The valid values for `day` are `1..=366`. Note though that `366` is
3235    /// only valid for leap years.
3236    ///
3237    /// This overrides any previous day settings.
3238    ///
3239    /// # Errors
3240    ///
3241    /// This returns an error when [`DateWith::build`] is called if the given
3242    /// day is outside the allowed range of `1..=366`, or when a value of `366`
3243    /// is given for a non-leap year.
3244    ///
3245    /// # Example
3246    ///
3247    /// This demonstrates that if a year is a leap year, then `60` corresponds
3248    /// to February 29:
3249    ///
3250    /// ```
3251    /// use jiff::civil::date;
3252    ///
3253    /// let d = date(2024, 1, 1);
3254    /// assert_eq!(d.with().day_of_year(60).build()?, date(2024, 2, 29));
3255    ///
3256    /// # Ok::<(), Box<dyn std::error::Error>>(())
3257    /// ```
3258    ///
3259    /// But for non-leap years, day 60 is March 1:
3260    ///
3261    /// ```
3262    /// use jiff::civil::date;
3263    ///
3264    /// let d = date(2023, 1, 1);
3265    /// assert_eq!(d.with().day_of_year(60).build()?, date(2023, 3, 1));
3266    ///
3267    /// # Ok::<(), Box<dyn std::error::Error>>(())
3268    /// ```
3269    ///
3270    /// And using `366` for a non-leap year will result in an error, since
3271    /// non-leap years only have 365 days:
3272    ///
3273    /// ```
3274    /// use jiff::civil::date;
3275    ///
3276    /// let d = date(2023, 1, 1);
3277    /// assert!(d.with().day_of_year(366).build().is_err());
3278    /// // The maximal year is not a leap year, so it returns an error too.
3279    /// let d = date(9999, 1, 1);
3280    /// assert!(d.with().day_of_year(366).build().is_err());
3281    /// ```
3282    #[inline]
3283    pub fn day_of_year(self, day: i16) -> DateWith {
3284        DateWith { day: Some(DateWithDay::OfYear(day)), ..self }
3285    }
3286
3287    /// Set the day field on a [`Date`] via the ordinal number of a day within
3288    /// a year, but ignoring leap years.
3289    ///
3290    /// When used, any settings for month are ignored since the month is
3291    /// determined by the day of the year.
3292    ///
3293    /// The valid values for `day` are `1..=365`. The value `365` always
3294    /// corresponds to the last day of the year, even for leap years. It is
3295    /// impossible for this routine to return a date corresponding to February
3296    /// 29.
3297    ///
3298    /// This overrides any previous day settings.
3299    ///
3300    /// # Errors
3301    ///
3302    /// This returns an error when [`DateWith::build`] is called if the given
3303    /// day is outside the allowed range of `1..=365`.
3304    ///
3305    /// # Example
3306    ///
3307    /// This demonstrates that `60` corresponds to March 1, regardless of
3308    /// whether the year is a leap year or not:
3309    ///
3310    /// ```
3311    /// use jiff::civil::date;
3312    ///
3313    /// assert_eq!(
3314    ///     date(2023, 1, 1).with().day_of_year_no_leap(60).build()?,
3315    ///     date(2023, 3, 1),
3316    /// );
3317    ///
3318    /// assert_eq!(
3319    ///     date(2024, 1, 1).with().day_of_year_no_leap(60).build()?,
3320    ///     date(2024, 3, 1),
3321    /// );
3322    ///
3323    /// # Ok::<(), Box<dyn std::error::Error>>(())
3324    /// ```
3325    ///
3326    /// And using `365` for any year will always yield the last day of the
3327    /// year:
3328    ///
3329    /// ```
3330    /// use jiff::civil::date;
3331    ///
3332    /// let d = date(2023, 1, 1);
3333    /// assert_eq!(
3334    ///     d.with().day_of_year_no_leap(365).build()?,
3335    ///     d.last_of_year(),
3336    /// );
3337    ///
3338    /// let d = date(2024, 1, 1);
3339    /// assert_eq!(
3340    ///     d.with().day_of_year_no_leap(365).build()?,
3341    ///     d.last_of_year(),
3342    /// );
3343    ///
3344    /// let d = date(9999, 1, 1);
3345    /// assert_eq!(
3346    ///     d.with().day_of_year_no_leap(365).build()?,
3347    ///     d.last_of_year(),
3348    /// );
3349    ///
3350    /// # Ok::<(), Box<dyn std::error::Error>>(())
3351    /// ```
3352    ///
3353    /// A value of `366` is out of bounds, even for leap years:
3354    ///
3355    /// ```
3356    /// use jiff::civil::date;
3357    ///
3358    /// let d = date(2024, 1, 1);
3359    /// assert!(d.with().day_of_year_no_leap(366).build().is_err());
3360    /// ```
3361    #[inline]
3362    pub fn day_of_year_no_leap(self, day: i16) -> DateWith {
3363        DateWith { day: Some(DateWithDay::OfYearNoLeap(day)), ..self }
3364    }
3365}
3366
3367/// Encodes the "with year" option of [`DateWith`].
3368///
3369/// This encodes the invariant that `DateWith::year` and `DateWith::era_year`
3370/// are mutually exclusive and override each other.
3371#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DateWithYear {
}
#[automatically_derived]impl ::core::clone::Clone for DateWithYear {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<i16>;
        let _: ::core::clone::AssertParamIsClone<Era>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for DateWithYear { }Copy, #[automatically_derived]impl ::core::fmt::Debug for DateWithYear {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Jiff(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Jiff",
                    &__self_0),
            Self::EraYear(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "EraYear", __self_0, &__self_1),
        }
    }
}Debug)]
3372enum DateWithYear {
3373    Jiff(i16),
3374    EraYear(i16, Era),
3375}
3376
3377/// Encodes the "with day" option of [`DateWith`].
3378///
3379/// This encodes the invariant that `DateWith::day`, `DateWith::day_of_year`
3380/// and `DateWith::day_of_year_no_leap` are all mutually exclusive and override
3381/// each other.
3382///
3383/// Note that when "day of year" or "day of year no leap" are used, then if a
3384/// day of month is set, it is ignored.
3385#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DateWithDay {
}
#[automatically_derived]impl ::core::clone::Clone for DateWithDay {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<i8>;
        let _: ::core::clone::AssertParamIsClone<i16>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for DateWithDay { }Copy, #[automatically_derived]impl ::core::fmt::Debug for DateWithDay {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::OfMonth(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OfMonth", &__self_0),
            Self::OfYear(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OfYear", &__self_0),
            Self::OfYearNoLeap(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OfYearNoLeap", &__self_0),
        }
    }
}Debug)]
3386enum DateWithDay {
3387    OfMonth(i8),
3388    OfYear(i16),
3389    OfYearNoLeap(i16),
3390}
3391
3392/// Adds or subtracts `sign` from the given `year`/`month`.
3393///
3394/// If month overflows in either direction, then the `year` returned is
3395/// adjusted as appropriate.
3396fn month_add_one(
3397    mut year: i16,
3398    mut month: i8,
3399    delta: Sign,
3400) -> Result<(i16, i8), Error> {
3401    month += delta.as_i8();
3402    if month < 1 {
3403        year -= 1;
3404        month += 12;
3405    } else if month > 12 {
3406        year += 1;
3407        month -= 12;
3408    }
3409    let year = b::Year::check(year)?;
3410    Ok((year, month))
3411}
3412
3413/// Adds the given span of months to the `month` given.
3414///
3415/// If adding (or subtracting) would result in overflowing the `month` value,
3416/// then the amount by which it overflowed, in units of years, is returned. For
3417/// example, adding 14 months to the month `3` (March) will result in returning
3418/// the month `5` (May) with `1` year of overflow.
3419///
3420/// # Preconditions
3421///
3422/// Callers must ensure that `span` is in bounds for `b::SpanMonths`.
3423fn month_add_overflowing(month: i8, span: i32) -> (i8, i16) {
3424    if true {
    if !b::SpanMonths::check(span).is_ok() {
        ::core::panicking::panic("assertion failed: b::SpanMonths::check(span).is_ok()")
    };
};debug_assert!(b::SpanMonths::check(span).is_ok());
3425    let month = i32::from(month);
3426    let total = month - 1 + span;
3427    let years = total.div_euclid(12);
3428    let month = total.rem_euclid(12) + 1;
3429    // OK because `month` is derived from `% 12`, so must fit into an `i8`. And
3430    // because `years` is derived from `([1-12] - 1 + SpanMonths) / 12` where
3431    // the maximum `SpanMonths` is `239976`. Thus, the result is guaranteed to
3432    // fit into an `i16`.
3433    (month as i8, years as i16)
3434}
3435
3436#[cfg(test)]
3437mod tests {
3438    use std::io::Cursor;
3439
3440    use crate::{Timestamp, ToSpan, civil::date, span::span_eq, tz::TimeZone};
3441
3442    use super::*;
3443
3444    #[test]
3445    fn t_from_unix() {
3446        fn date_from_timestamp(timestamp: Timestamp) -> Date {
3447            timestamp.to_zoned_datetime(TimeZone::UTC).datetime().date()
3448        }
3449
3450        assert_eq!(
3451            date(1970, 1, 1),
3452            date_from_timestamp(Timestamp::new(0, 0).unwrap()),
3453        );
3454        assert_eq!(
3455            date(1969, 12, 31),
3456            date_from_timestamp(Timestamp::new(-1, 0).unwrap()),
3457        );
3458        assert_eq!(
3459            date(1969, 12, 31),
3460            date_from_timestamp(Timestamp::new(-86_400, 0).unwrap()),
3461        );
3462        assert_eq!(
3463            date(1969, 12, 30),
3464            date_from_timestamp(Timestamp::new(-86_401, 0).unwrap()),
3465        );
3466        assert_eq!(
3467            date(-9999, 1, 2),
3468            date_from_timestamp(
3469                Timestamp::new(b::UnixEpochSeconds::MIN, 0).unwrap()
3470            ),
3471        );
3472        assert_eq!(
3473            date(9999, 12, 30),
3474            date_from_timestamp(
3475                Timestamp::new(b::UnixEpochSeconds::MAX, 0).unwrap()
3476            ),
3477        );
3478    }
3479
3480    #[test]
3481    #[cfg(not(miri))]
3482    fn all_days_to_date_roundtrip() {
3483        for rd in -100_000..=100_000 {
3484            let day = jcore::civil::UnixEpochDay::new(rd).unwrap();
3485            let date = Date::from_unix_epoch_day(day);
3486            let got = date.to_unix_epoch_day();
3487            assert_eq!(rd, got.day(), "for date {date:?}");
3488        }
3489    }
3490
3491    #[test]
3492    #[cfg(not(miri))]
3493    fn all_date_to_days_roundtrip() {
3494        let year_range = 2000..=2500;
3495        // let year_range = -9999..=9999;
3496        for year in year_range {
3497            for month in b::Month::MIN..=b::Month::MAX {
3498                for day in 1..=jcore::civil::days_in_month(year, month) {
3499                    let date = date(year, month, day);
3500                    let rd = date.to_unix_epoch_day();
3501                    let got = Date::from_unix_epoch_day(rd);
3502                    assert_eq!(date, got, "for date {date:?}");
3503                }
3504            }
3505        }
3506    }
3507
3508    #[test]
3509    #[cfg(not(miri))]
3510    fn all_date_to_iso_week_date_roundtrip() {
3511        let year_range = 2000..=2500;
3512        for year in year_range {
3513            for month in [1, 2, 4] {
3514                for day in 20..=jcore::civil::days_in_month(year, month) {
3515                    let date = date(year, month, day);
3516                    let wd = date.iso_week_date();
3517                    let got = wd.date();
3518                    assert_eq!(
3519                        date, got,
3520                        "for date {date:?}, and ISO week date {wd:?}"
3521                    );
3522                }
3523            }
3524        }
3525
3526        let year_range = -9999..=-9500;
3527        for year in year_range {
3528            for month in [1, 2, 4] {
3529                for day in 20..=jcore::civil::days_in_month(year, month) {
3530                    let date = date(year, month, day);
3531                    let wd = date.iso_week_date();
3532                    let got = wd.date();
3533                    assert_eq!(
3534                        date, got,
3535                        "for date {date:?}, and ISO week date {wd:?}"
3536                    );
3537                }
3538            }
3539        }
3540    }
3541
3542    #[test]
3543    fn add_constrained() {
3544        use crate::ToSpan;
3545
3546        let d1 = date(2023, 3, 31);
3547        let d2 = d1.checked_add(1.months().days(1)).unwrap();
3548        assert_eq!(d2, date(2023, 5, 1));
3549    }
3550
3551    #[test]
3552    fn since_years() {
3553        let d1 = date(2023, 4, 15);
3554        let d2 = date(2019, 2, 22);
3555        let span = d1.since((Unit::Year, d2)).unwrap();
3556        span_eq!(span, 4.years().months(1).days(21));
3557        let span = d2.since((Unit::Year, d1)).unwrap();
3558        span_eq!(span, -4.years().months(1).days(24));
3559
3560        let d1 = date(2023, 2, 22);
3561        let d2 = date(2019, 4, 15);
3562        let span = d1.since((Unit::Year, d2)).unwrap();
3563        span_eq!(span, 3.years().months(10).days(7));
3564        let span = d2.since((Unit::Year, d1)).unwrap();
3565        span_eq!(span, -3.years().months(10).days(7));
3566
3567        let d1 = date(9999, 12, 31);
3568        let d2 = date(-9999, 1, 1);
3569        let span = d1.since((Unit::Year, d2)).unwrap();
3570        span_eq!(span, 19998.years().months(11).days(30));
3571        let span = d2.since((Unit::Year, d1)).unwrap();
3572        span_eq!(span, -19998.years().months(11).days(30));
3573    }
3574
3575    #[test]
3576    fn since_months() {
3577        let d1 = date(2024, 7, 24);
3578        let d2 = date(2024, 2, 22);
3579        let span = d1.since((Unit::Month, d2)).unwrap();
3580        span_eq!(span, 5.months().days(2));
3581        let span = d2.since((Unit::Month, d1)).unwrap();
3582        span_eq!(span, -5.months().days(2));
3583        assert_eq!(d2, d1.checked_sub(5.months().days(2)).unwrap());
3584        assert_eq!(d1, d2.checked_sub(-5.months().days(2)).unwrap());
3585
3586        let d1 = date(2024, 7, 15);
3587        let d2 = date(2024, 2, 22);
3588        let span = d1.since((Unit::Month, d2)).unwrap();
3589        span_eq!(span, 4.months().days(22));
3590        let span = d2.since((Unit::Month, d1)).unwrap();
3591        span_eq!(span, -4.months().days(23));
3592        assert_eq!(d2, d1.checked_sub(4.months().days(22)).unwrap());
3593        assert_eq!(d1, d2.checked_sub(-4.months().days(23)).unwrap());
3594
3595        let d1 = date(2023, 4, 15);
3596        let d2 = date(2023, 2, 22);
3597        let span = d1.since((Unit::Month, d2)).unwrap();
3598        span_eq!(span, 1.month().days(21));
3599        let span = d2.since((Unit::Month, d1)).unwrap();
3600        span_eq!(span, -1.month().days(24));
3601        assert_eq!(d2, d1.checked_sub(1.month().days(21)).unwrap());
3602        assert_eq!(d1, d2.checked_sub(-1.month().days(24)).unwrap());
3603
3604        let d1 = date(2023, 4, 15);
3605        let d2 = date(2019, 2, 22);
3606        let span = d1.since((Unit::Month, d2)).unwrap();
3607        span_eq!(span, 49.months().days(21));
3608        let span = d2.since((Unit::Month, d1)).unwrap();
3609        span_eq!(span, -49.months().days(24));
3610    }
3611
3612    #[test]
3613    fn since_weeks() {
3614        let d1 = date(2024, 7, 15);
3615        let d2 = date(2024, 6, 22);
3616        let span = d1.since((Unit::Week, d2)).unwrap();
3617        span_eq!(span, 3.weeks().days(2));
3618        let span = d2.since((Unit::Week, d1)).unwrap();
3619        span_eq!(span, -3.weeks().days(2));
3620    }
3621
3622    #[test]
3623    fn since_days() {
3624        let d1 = date(2024, 7, 15);
3625        let d2 = date(2024, 2, 22);
3626        let span = d1.since((Unit::Day, d2)).unwrap();
3627        span_eq!(span, 144.days());
3628        let span = d2.since((Unit::Day, d1)).unwrap();
3629        span_eq!(span, -144.days());
3630    }
3631
3632    #[test]
3633    fn until_month_lengths() {
3634        let jan1 = date(2020, 1, 1);
3635        let feb1 = date(2020, 2, 1);
3636        let mar1 = date(2020, 3, 1);
3637
3638        span_eq!(jan1.until(feb1).unwrap(), 31.days());
3639        span_eq!(jan1.until((Unit::Month, feb1)).unwrap(), 1.month());
3640        span_eq!(feb1.until(mar1).unwrap(), 29.days());
3641        span_eq!(feb1.until((Unit::Month, mar1)).unwrap(), 1.month());
3642        span_eq!(jan1.until(mar1).unwrap(), 60.days());
3643        span_eq!(jan1.until((Unit::Month, mar1)).unwrap(), 2.months());
3644    }
3645
3646    // Ref: https://github.com/tc39/proposal-temporal/issues/2845#issuecomment-2121057896
3647    #[test]
3648    fn since_until_not_commutative() {
3649        // Temporal.PlainDate.from("2020-04-30").since("2020-02-29", {largestUnit: "months"})
3650        // // => P2M
3651        // Temporal.PlainDate.from("2020-02-29").until("2020-04-30", {largestUnit: "months"})
3652        // // => P2M1D
3653        let d1 = date(2020, 4, 30);
3654        let d2 = date(2020, 2, 29);
3655
3656        let since = d1.since((Unit::Month, d2)).unwrap();
3657        span_eq!(since, 2.months());
3658
3659        let until = d2.until((Unit::Month, d1)).unwrap();
3660        span_eq!(until, 2.months().days(1));
3661    }
3662
3663    // Ref: https://github.com/tc39/proposal-temporal/issues/2893
3664    #[test]
3665    fn until_weeks_round() {
3666        use crate::{RoundMode, SpanRound};
3667
3668        let earlier = date(2019, 1, 8);
3669        let later = date(2021, 9, 7);
3670        let span = earlier.until((Unit::Week, later)).unwrap();
3671        span_eq!(span, 139.weeks());
3672
3673        let options = SpanRound::new()
3674            .smallest(Unit::Week)
3675            .mode(RoundMode::HalfExpand)
3676            .relative(earlier.to_datetime(Time::midnight()));
3677        let rounded = span.round(options).unwrap();
3678        span_eq!(rounded, 139.weeks());
3679    }
3680
3681    // This test checks current behavior, but I think it's wrong. I think the
3682    // results below should be 11 months and 1 month.
3683    //
3684    // 2026-02-01: No, actually, the results here match what Temporal does:
3685    //
3686    // >> date = Temporal.PlainDate.from("2023-05-31")
3687    // >> date.until("2024-04-30", {largestUnit: 'month'}).toString()
3688    // "P10M30D"
3689    // >> date.until("2023-06-30", {largestUnit: 'month'}).toString()
3690    // "P30D"
3691    //
3692    // The specific reasoning here has to do with a trade-off where alternative
3693    // algorithms result in even less intuitive results. See 2535 linked below.
3694    //
3695    // Ref: https://github.com/tc39/proposal-temporal/issues/2919
3696    // Ref: https://github.com/tc39/proposal-temporal/issues/2535
3697    #[test]
3698    fn until_months_no_balance() {
3699        let sp =
3700            date(2023, 5, 31).until((Unit::Month, date(2024, 4, 30))).unwrap();
3701        span_eq!(sp, 10.months().days(30));
3702
3703        let sp =
3704            date(2023, 5, 31).until((Unit::Month, date(2023, 6, 30))).unwrap();
3705        span_eq!(sp, 30.days());
3706    }
3707
3708    #[test]
3709    fn until_extremes() {
3710        let d1 = date(-9999, 12, 1);
3711        let d2 = date(-9999, 1, 2);
3712        span_eq!(d1.until((Unit::Month, d2)).unwrap(), -10.months().days(30));
3713
3714        let d1 = date(9999, 1, 2);
3715        let d2 = date(9999, 12, 1);
3716        span_eq!(d1.until((Unit::Month, d2)).unwrap(), 10.months().days(29));
3717    }
3718
3719    #[test]
3720    fn test_month_add() {
3721        let add =
3722            |year: i16, month: i8, delta: i8| -> Result<(i16, i8), Error> {
3723                month_add_one(year, month, Sign::from(delta))
3724            };
3725
3726        assert_eq!(add(2024, 1, 1).unwrap(), (2024, 2));
3727        assert_eq!(add(2024, 1, -1).unwrap(), (2023, 12));
3728        assert_eq!(add(2024, 12, 1).unwrap(), (2025, 1));
3729        assert_eq!(add(9999, 12, -1).unwrap(), (9999, 11));
3730        assert_eq!(add(-9999, 1, 1).unwrap(), (-9999, 2));
3731
3732        assert!(add(9999, 12, 1).is_err());
3733        assert!(add(-9999, 1, -1).is_err());
3734    }
3735
3736    #[test]
3737    fn test_month_add_overflowing() {
3738        let month_add = |month, span| month_add_overflowing(month, span);
3739
3740        assert_eq!((1, 0), month_add(1, 0));
3741        assert_eq!((12, 0), month_add(1, 11));
3742        assert_eq!((1, 1), month_add(1, 12));
3743        assert_eq!((2, 1), month_add(1, 13));
3744        assert_eq!((9, 1), month_add(1, 20));
3745        assert_eq!((12, 19998), month_add(12, b::SpanMonths::MAX));
3746
3747        assert_eq!((12, -1), month_add(1, -1));
3748        assert_eq!((11, -1), month_add(1, -2));
3749        assert_eq!((1, -1), month_add(1, -12));
3750        assert_eq!((12, -2), month_add(1, -13));
3751    }
3752
3753    #[test]
3754    fn date_size() {
3755        #[cfg(debug_assertions)]
3756        {
3757            assert_eq!(4, core::mem::size_of::<Date>());
3758        }
3759        #[cfg(not(debug_assertions))]
3760        {
3761            assert_eq!(4, core::mem::size_of::<Date>());
3762        }
3763    }
3764
3765    #[cfg(not(miri))]
3766    quickcheck::quickcheck! {
3767        fn prop_checked_add_then_sub(
3768            d1: Date,
3769            span: Span
3770        ) -> quickcheck::TestResult {
3771            // Force our span to have no units greater than days.
3772            let span = if span.largest_unit() <= Unit::Day {
3773                span
3774            } else {
3775                let round = SpanRound::new().largest(Unit::Day).relative(d1);
3776                let Ok(span) = span.round(round) else {
3777                    return quickcheck::TestResult::discard();
3778                };
3779                span
3780            };
3781            let Ok(d2) = d1.checked_add(span) else {
3782                return quickcheck::TestResult::discard();
3783            };
3784            let got = d2.checked_sub(span).unwrap();
3785            quickcheck::TestResult::from_bool(d1 == got)
3786        }
3787
3788        fn prop_checked_sub_then_add(
3789            d1: Date,
3790            span: Span
3791        ) -> quickcheck::TestResult {
3792            // Force our span to have no units greater than days.
3793            let span = if span.largest_unit() <= Unit::Day {
3794                span
3795            } else {
3796                let round = SpanRound::new().largest(Unit::Day).relative(d1);
3797                let Ok(span) = span.round(round) else {
3798                    return quickcheck::TestResult::discard();
3799                };
3800                span
3801            };
3802            let Ok(d2) = d1.checked_sub(span) else {
3803                return quickcheck::TestResult::discard();
3804            };
3805            let got = d2.checked_add(span).unwrap();
3806            quickcheck::TestResult::from_bool(d1 == got)
3807        }
3808
3809        fn prop_since_then_add(d1: Date, d2: Date) -> bool {
3810            let span = d1.since(d2).unwrap();
3811            let got = d2.checked_add(span).unwrap();
3812            d1 == got
3813        }
3814
3815        fn prop_until_then_sub(d1: Date, d2: Date) -> bool {
3816            let span = d1.until(d2).unwrap();
3817            let got = d2.checked_sub(span).unwrap();
3818            d1 == got
3819        }
3820    }
3821
3822    /// # `serde` deserializer compatibility test
3823    ///
3824    /// Serde YAML used to be unable to deserialize `jiff` types,
3825    /// as deserializing from bytes is not supported by the deserializer.
3826    ///
3827    /// - <https://github.com/BurntSushi/jiff/issues/138>
3828    /// - <https://github.com/BurntSushi/jiff/discussions/148>
3829    #[test]
3830    fn civil_date_deserialize_yaml() {
3831        let expected = date(2024, 10, 31);
3832
3833        let deserialized: Date = serde_yaml::from_str("2024-10-31").unwrap();
3834
3835        assert_eq!(deserialized, expected);
3836
3837        let deserialized: Date =
3838            serde_yaml::from_slice("2024-10-31".as_bytes()).unwrap();
3839
3840        assert_eq!(deserialized, expected);
3841
3842        let cursor = Cursor::new(b"2024-10-31");
3843        let deserialized: Date = serde_yaml::from_reader(cursor).unwrap();
3844
3845        assert_eq!(deserialized, expected);
3846    }
3847
3848    /// Regression test where converting to `IDate` and back to do the
3849    /// calculation was FUBAR.
3850    #[test]
3851    fn nth_weekday_of_month() {
3852        let d1 = date(1998, 1, 1);
3853        let d2 = d1.nth_weekday_of_month(5, Weekday::Saturday).unwrap();
3854        assert_eq!(d2, date(1998, 1, 31));
3855    }
3856
3857    /// Tests some extreme values for `Date::nth_weekday`.
3858    #[test]
3859    fn nth_weekday_extreme() {
3860        let weeks = 1043497;
3861
3862        let d1 = date(-9999, 1, 1);
3863        let d2 = d1.nth_weekday(weeks, Weekday::Monday).unwrap();
3864        assert_eq!(d2, date(9999, 12, 27));
3865        assert!(d1.nth_weekday(weeks + 1, Weekday::Monday).is_err());
3866
3867        let d1 = date(9999, 12, 31);
3868        let d2 = d1.nth_weekday(-weeks, Weekday::Friday).unwrap();
3869        assert_eq!(d2, date(-9999, 1, 5));
3870        assert!(d1.nth_weekday(weeks - 1, Weekday::Friday).is_err());
3871    }
3872
3873    #[test]
3874    fn date_invalid_day() {
3875        assert!(Date::new(1998, 1, 0).is_err());
3876        assert!(Date::new(1998, 1, -1).is_err());
3877        assert!(Date::new(1998, 2, 29).is_err());
3878        assert!(Date::new(2004, 2, 29).is_ok());
3879        assert!(Date::new(2026, 3, 0).is_err());
3880        assert!(Date::new(2026, 3, -1).is_err());
3881    }
3882}