chrono/
date.rs

1// This is a part of Chrono.
2// See README.md and LICENSE.txt for details.
3
4//! ISO 8601 calendar date with time zone.
5#![allow(deprecated)]
6
7#[cfg(any(feature = "alloc", feature = "std"))]
8use core::borrow::Borrow;
9use core::cmp::Ordering;
10use core::ops::{Add, AddAssign, Sub, SubAssign};
11use core::{fmt, hash};
12
13#[cfg(feature = "rkyv")]
14use rkyv::{Archive, Deserialize, Serialize};
15
16use crate::duration::Duration as OldDuration;
17#[cfg(feature = "unstable-locales")]
18use crate::format::Locale;
19#[cfg(any(feature = "alloc", feature = "std"))]
20use crate::format::{DelayedFormat, Item, StrftimeItems};
21use crate::naive::{IsoWeek, NaiveDate, NaiveTime};
22use crate::offset::{TimeZone, Utc};
23use crate::DateTime;
24use crate::{Datelike, Weekday};
25
26/// ISO 8601 calendar date with time zone.
27///
28/// You almost certainly want to be using a [`NaiveDate`] instead of this type.
29///
30/// This type primarily exists to aid in the construction of DateTimes that
31/// have a timezone by way of the [`TimeZone`] datelike constructors (e.g.
32/// [`TimeZone::ymd`]).
33///
34/// This type should be considered ambiguous at best, due to the inherent lack
35/// of precision required for the time zone resolution.
36///
37/// There are some guarantees on the usage of `Date<Tz>`:
38///
39/// - If properly constructed via [`TimeZone::ymd`] and others without an error,
40///   the corresponding local date should exist for at least a moment.
41///   (It may still have a gap from the offset changes.)
42///
43/// - The `TimeZone` is free to assign *any* [`Offset`](crate::offset::Offset) to the
44///   local date, as long as that offset did occur in given day.
45///
46///   For example, if `2015-03-08T01:59-08:00` is followed by `2015-03-08T03:00-07:00`,
47///   it may produce either `2015-03-08-08:00` or `2015-03-08-07:00`
48///   but *not* `2015-03-08+00:00` and others.
49///
50/// - Once constructed as a full `DateTime`, [`DateTime::date`] and other associated
51///   methods should return those for the original `Date`. For example, if `dt =
52///   tz.ymd_opt(y,m,d).unwrap().hms(h,n,s)` were valid, `dt.date() == tz.ymd_opt(y,m,d).unwrap()`.
53///
54/// - The date is timezone-agnostic up to one day (i.e. practically always),
55///   so the local date and UTC date should be equal for most cases
56///   even though the raw calculation between `NaiveDate` and `Duration` may not.
57#[deprecated(since = "0.4.23", note = "Use `NaiveDate` or `DateTime<Tz>` instead")]
58#[derive(Clone)]
59#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
60pub struct Date<Tz: TimeZone> {
61    date: NaiveDate,
62    offset: Tz::Offset,
63}
64
65/// The minimum possible `Date`.
66#[allow(deprecated)]
67#[deprecated(since = "0.4.20", note = "Use Date::MIN_UTC instead")]
68pub const MIN_DATE: Date<Utc> = Date::<Utc>::MIN_UTC;
69/// The maximum possible `Date`.
70#[allow(deprecated)]
71#[deprecated(since = "0.4.20", note = "Use Date::MAX_UTC instead")]
72pub const MAX_DATE: Date<Utc> = Date::<Utc>::MAX_UTC;
73
74impl<Tz: TimeZone> Date<Tz> {
75    /// Makes a new `Date` with given *UTC* date and offset.
76    /// The local date should be constructed via the `TimeZone` trait.
77    #[inline]
78    #[must_use]
79    pub fn from_utc(date: NaiveDate, offset: Tz::Offset) -> Date<Tz> {
80        Date { date, offset }
81    }
82
83    /// Makes a new `DateTime` from the current date and given `NaiveTime`.
84    /// The offset in the current date is preserved.
85    ///
86    /// Returns `None` on invalid datetime.
87    #[inline]
88    #[must_use]
89    pub fn and_time(&self, time: NaiveTime) -> Option<DateTime<Tz>> {
90        let localdt = self.naive_local().and_time(time);
91        self.timezone().from_local_datetime(&localdt).single()
92    }
93
94    /// Makes a new `DateTime` from the current date, hour, minute and second.
95    /// The offset in the current date is preserved.
96    ///
97    /// Panics on invalid hour, minute and/or second.
98    #[deprecated(since = "0.4.23", note = "Use and_hms_opt() instead")]
99    #[inline]
100    #[must_use]
101    pub fn and_hms(&self, hour: u32, min: u32, sec: u32) -> DateTime<Tz> {
102        self.and_hms_opt(hour, min, sec).expect("invalid time")
103    }
104
105    /// Makes a new `DateTime` from the current date, hour, minute and second.
106    /// The offset in the current date is preserved.
107    ///
108    /// Returns `None` on invalid hour, minute and/or second.
109    #[inline]
110    #[must_use]
111    pub fn and_hms_opt(&self, hour: u32, min: u32, sec: u32) -> Option<DateTime<Tz>> {
112        NaiveTime::from_hms_opt(hour, min, sec).and_then(|time| self.and_time(time))
113    }
114
115    /// Makes a new `DateTime` from the current date, hour, minute, second and millisecond.
116    /// The millisecond part can exceed 1,000 in order to represent the leap second.
117    /// The offset in the current date is preserved.
118    ///
119    /// Panics on invalid hour, minute, second and/or millisecond.
120    #[deprecated(since = "0.4.23", note = "Use and_hms_milli_opt() instead")]
121    #[inline]
122    #[must_use]
123    pub fn and_hms_milli(&self, hour: u32, min: u32, sec: u32, milli: u32) -> DateTime<Tz> {
124        self.and_hms_milli_opt(hour, min, sec, milli).expect("invalid time")
125    }
126
127    /// Makes a new `DateTime` from the current date, hour, minute, second and millisecond.
128    /// The millisecond part can exceed 1,000 in order to represent the leap second.
129    /// The offset in the current date is preserved.
130    ///
131    /// Returns `None` on invalid hour, minute, second and/or millisecond.
132    #[inline]
133    #[must_use]
134    pub fn and_hms_milli_opt(
135        &self,
136        hour: u32,
137        min: u32,
138        sec: u32,
139        milli: u32,
140    ) -> Option<DateTime<Tz>> {
141        NaiveTime::from_hms_milli_opt(hour, min, sec, milli).and_then(|time| self.and_time(time))
142    }
143
144    /// Makes a new `DateTime` from the current date, hour, minute, second and microsecond.
145    /// The microsecond part can exceed 1,000,000 in order to represent the leap second.
146    /// The offset in the current date is preserved.
147    ///
148    /// Panics on invalid hour, minute, second and/or microsecond.
149    #[deprecated(since = "0.4.23", note = "Use and_hms_micro_opt() instead")]
150    #[inline]
151    #[must_use]
152    pub fn and_hms_micro(&self, hour: u32, min: u32, sec: u32, micro: u32) -> DateTime<Tz> {
153        self.and_hms_micro_opt(hour, min, sec, micro).expect("invalid time")
154    }
155
156    /// Makes a new `DateTime` from the current date, hour, minute, second and microsecond.
157    /// The microsecond part can exceed 1,000,000 in order to represent the leap second.
158    /// The offset in the current date is preserved.
159    ///
160    /// Returns `None` on invalid hour, minute, second and/or microsecond.
161    #[inline]
162    #[must_use]
163    pub fn and_hms_micro_opt(
164        &self,
165        hour: u32,
166        min: u32,
167        sec: u32,
168        micro: u32,
169    ) -> Option<DateTime<Tz>> {
170        NaiveTime::from_hms_micro_opt(hour, min, sec, micro).and_then(|time| self.and_time(time))
171    }
172
173    /// Makes a new `DateTime` from the current date, hour, minute, second and nanosecond.
174    /// The nanosecond part can exceed 1,000,000,000 in order to represent the leap second.
175    /// The offset in the current date is preserved.
176    ///
177    /// Panics on invalid hour, minute, second and/or nanosecond.
178    #[deprecated(since = "0.4.23", note = "Use and_hms_nano_opt() instead")]
179    #[inline]
180    #[must_use]
181    pub fn and_hms_nano(&self, hour: u32, min: u32, sec: u32, nano: u32) -> DateTime<Tz> {
182        self.and_hms_nano_opt(hour, min, sec, nano).expect("invalid time")
183    }
184
185    /// Makes a new `DateTime` from the current date, hour, minute, second and nanosecond.
186    /// The nanosecond part can exceed 1,000,000,000 in order to represent the leap second.
187    /// The offset in the current date is preserved.
188    ///
189    /// Returns `None` on invalid hour, minute, second and/or nanosecond.
190    #[inline]
191    #[must_use]
192    pub fn and_hms_nano_opt(
193        &self,
194        hour: u32,
195        min: u32,
196        sec: u32,
197        nano: u32,
198    ) -> Option<DateTime<Tz>> {
199        NaiveTime::from_hms_nano_opt(hour, min, sec, nano).and_then(|time| self.and_time(time))
200    }
201
202    /// Makes a new `Date` for the next date.
203    ///
204    /// Panics when `self` is the last representable date.
205    #[deprecated(since = "0.4.23", note = "Use succ_opt() instead")]
206    #[inline]
207    #[must_use]
208    pub fn succ(&self) -> Date<Tz> {
209        self.succ_opt().expect("out of bound")
210    }
211
212    /// Makes a new `Date` for the next date.
213    ///
214    /// Returns `None` when `self` is the last representable date.
215    #[inline]
216    #[must_use]
217    pub fn succ_opt(&self) -> Option<Date<Tz>> {
218        self.date.succ_opt().map(|date| Date::from_utc(date, self.offset.clone()))
219    }
220
221    /// Makes a new `Date` for the prior date.
222    ///
223    /// Panics when `self` is the first representable date.
224    #[deprecated(since = "0.4.23", note = "Use pred_opt() instead")]
225    #[inline]
226    #[must_use]
227    pub fn pred(&self) -> Date<Tz> {
228        self.pred_opt().expect("out of bound")
229    }
230
231    /// Makes a new `Date` for the prior date.
232    ///
233    /// Returns `None` when `self` is the first representable date.
234    #[inline]
235    #[must_use]
236    pub fn pred_opt(&self) -> Option<Date<Tz>> {
237        self.date.pred_opt().map(|date| Date::from_utc(date, self.offset.clone()))
238    }
239
240    /// Retrieves an associated offset from UTC.
241    #[inline]
242    #[must_use]
243    pub fn offset(&self) -> &Tz::Offset {
244        &self.offset
245    }
246
247    /// Retrieves an associated time zone.
248    #[inline]
249    #[must_use]
250    pub fn timezone(&self) -> Tz {
251        TimeZone::from_offset(&self.offset)
252    }
253
254    /// Changes the associated time zone.
255    /// This does not change the actual `Date` (but will change the string representation).
256    #[inline]
257    #[must_use]
258    pub fn with_timezone<Tz2: TimeZone>(&self, tz: &Tz2) -> Date<Tz2> {
259        tz.from_utc_date(&self.date)
260    }
261
262    /// Adds given `Duration` to the current date.
263    ///
264    /// Returns `None` when it will result in overflow.
265    #[inline]
266    #[must_use]
267    pub fn checked_add_signed(self, rhs: OldDuration) -> Option<Date<Tz>> {
268        let date = self.date.checked_add_signed(rhs)?;
269        Some(Date { date, offset: self.offset })
270    }
271
272    /// Subtracts given `Duration` from the current date.
273    ///
274    /// Returns `None` when it will result in overflow.
275    #[inline]
276    #[must_use]
277    pub fn checked_sub_signed(self, rhs: OldDuration) -> Option<Date<Tz>> {
278        let date = self.date.checked_sub_signed(rhs)?;
279        Some(Date { date, offset: self.offset })
280    }
281
282    /// Subtracts another `Date` from the current date.
283    /// Returns a `Duration` of integral numbers.
284    ///
285    /// This does not overflow or underflow at all,
286    /// as all possible output fits in the range of `Duration`.
287    #[inline]
288    #[must_use]
289    pub fn signed_duration_since<Tz2: TimeZone>(self, rhs: Date<Tz2>) -> OldDuration {
290        self.date.signed_duration_since(rhs.date)
291    }
292
293    /// Returns a view to the naive UTC date.
294    #[inline]
295    #[must_use]
296    pub fn naive_utc(&self) -> NaiveDate {
297        self.date
298    }
299
300    /// Returns a view to the naive local date.
301    ///
302    /// This is technically the same as [`naive_utc`](#method.naive_utc)
303    /// because the offset is restricted to never exceed one day,
304    /// but provided for the consistency.
305    #[inline]
306    #[must_use]
307    pub fn naive_local(&self) -> NaiveDate {
308        self.date
309    }
310
311    /// Returns the number of whole years from the given `base` until `self`.
312    #[must_use]
313    pub fn years_since(&self, base: Self) -> Option<u32> {
314        self.date.years_since(base.date)
315    }
316
317    /// The minimum possible `Date`.
318    pub const MIN_UTC: Date<Utc> = Date { date: NaiveDate::MIN, offset: Utc };
319    /// The maximum possible `Date`.
320    pub const MAX_UTC: Date<Utc> = Date { date: NaiveDate::MAX, offset: Utc };
321}
322
323/// Maps the local date to other date with given conversion function.
324fn map_local<Tz: TimeZone, F>(d: &Date<Tz>, mut f: F) -> Option<Date<Tz>>
325where
326    F: FnMut(NaiveDate) -> Option<NaiveDate>,
327{
328    f(d.naive_local()).and_then(|date| d.timezone().from_local_date(&date).single())
329}
330
331impl<Tz: TimeZone> Date<Tz>
332where
333    Tz::Offset: fmt::Display,
334{
335    /// Formats the date with the specified formatting items.
336    #[cfg(any(feature = "alloc", feature = "std"))]
337    #[cfg_attr(docsrs, doc(cfg(any(feature = "alloc", feature = "std"))))]
338    #[inline]
339    #[must_use]
340    pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I>
341    where
342        I: Iterator<Item = B> + Clone,
343        B: Borrow<Item<'a>>,
344    {
345        DelayedFormat::new_with_offset(Some(self.naive_local()), None, &self.offset, items)
346    }
347
348    /// Formats the date with the specified format string.
349    /// See the [`crate::format::strftime`] module
350    /// on the supported escape sequences.
351    #[cfg(any(feature = "alloc", feature = "std"))]
352    #[cfg_attr(docsrs, doc(cfg(any(feature = "alloc", feature = "std"))))]
353    #[inline]
354    #[must_use]
355    pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>> {
356        self.format_with_items(StrftimeItems::new(fmt))
357    }
358
359    /// Formats the date with the specified formatting items and locale.
360    #[cfg(feature = "unstable-locales")]
361    #[cfg_attr(docsrs, doc(cfg(feature = "unstable-locales")))]
362    #[inline]
363    #[must_use]
364    pub fn format_localized_with_items<'a, I, B>(
365        &self,
366        items: I,
367        locale: Locale,
368    ) -> DelayedFormat<I>
369    where
370        I: Iterator<Item = B> + Clone,
371        B: Borrow<Item<'a>>,
372    {
373        DelayedFormat::new_with_offset_and_locale(
374            Some(self.naive_local()),
375            None,
376            &self.offset,
377            items,
378            locale,
379        )
380    }
381
382    /// Formats the date with the specified format string and locale.
383    /// See the [`crate::format::strftime`] module
384    /// on the supported escape sequences.
385    #[cfg(feature = "unstable-locales")]
386    #[cfg_attr(docsrs, doc(cfg(feature = "unstable-locales")))]
387    #[inline]
388    #[must_use]
389    pub fn format_localized<'a>(
390        &self,
391        fmt: &'a str,
392        locale: Locale,
393    ) -> DelayedFormat<StrftimeItems<'a>> {
394        self.format_localized_with_items(StrftimeItems::new_with_locale(fmt, locale), locale)
395    }
396}
397
398impl<Tz: TimeZone> Datelike for Date<Tz> {
399    #[inline]
400    fn year(&self) -> i32 {
401        self.naive_local().year()
402    }
403    #[inline]
404    fn month(&self) -> u32 {
405        self.naive_local().month()
406    }
407    #[inline]
408    fn month0(&self) -> u32 {
409        self.naive_local().month0()
410    }
411    #[inline]
412    fn day(&self) -> u32 {
413        self.naive_local().day()
414    }
415    #[inline]
416    fn day0(&self) -> u32 {
417        self.naive_local().day0()
418    }
419    #[inline]
420    fn ordinal(&self) -> u32 {
421        self.naive_local().ordinal()
422    }
423    #[inline]
424    fn ordinal0(&self) -> u32 {
425        self.naive_local().ordinal0()
426    }
427    #[inline]
428    fn weekday(&self) -> Weekday {
429        self.naive_local().weekday()
430    }
431    #[inline]
432    fn iso_week(&self) -> IsoWeek {
433        self.naive_local().iso_week()
434    }
435
436    #[inline]
437    fn with_year(&self, year: i32) -> Option<Date<Tz>> {
438        map_local(self, |date| date.with_year(year))
439    }
440
441    #[inline]
442    fn with_month(&self, month: u32) -> Option<Date<Tz>> {
443        map_local(self, |date| date.with_month(month))
444    }
445
446    #[inline]
447    fn with_month0(&self, month0: u32) -> Option<Date<Tz>> {
448        map_local(self, |date| date.with_month0(month0))
449    }
450
451    #[inline]
452    fn with_day(&self, day: u32) -> Option<Date<Tz>> {
453        map_local(self, |date| date.with_day(day))
454    }
455
456    #[inline]
457    fn with_day0(&self, day0: u32) -> Option<Date<Tz>> {
458        map_local(self, |date| date.with_day0(day0))
459    }
460
461    #[inline]
462    fn with_ordinal(&self, ordinal: u32) -> Option<Date<Tz>> {
463        map_local(self, |date| date.with_ordinal(ordinal))
464    }
465
466    #[inline]
467    fn with_ordinal0(&self, ordinal0: u32) -> Option<Date<Tz>> {
468        map_local(self, |date| date.with_ordinal0(ordinal0))
469    }
470}
471
472// we need them as automatic impls cannot handle associated types
473impl<Tz: TimeZone> Copy for Date<Tz> where <Tz as TimeZone>::Offset: Copy {}
474unsafe impl<Tz: TimeZone> Send for Date<Tz> where <Tz as TimeZone>::Offset: Send {}
475
476impl<Tz: TimeZone, Tz2: TimeZone> PartialEq<Date<Tz2>> for Date<Tz> {
477    fn eq(&self, other: &Date<Tz2>) -> bool {
478        self.date == other.date
479    }
480}
481
482impl<Tz: TimeZone> Eq for Date<Tz> {}
483
484impl<Tz: TimeZone> PartialOrd for Date<Tz> {
485    fn partial_cmp(&self, other: &Date<Tz>) -> Option<Ordering> {
486        self.date.partial_cmp(&other.date)
487    }
488}
489
490impl<Tz: TimeZone> Ord for Date<Tz> {
491    fn cmp(&self, other: &Date<Tz>) -> Ordering {
492        self.date.cmp(&other.date)
493    }
494}
495
496impl<Tz: TimeZone> hash::Hash for Date<Tz> {
497    fn hash<H: hash::Hasher>(&self, state: &mut H) {
498        self.date.hash(state)
499    }
500}
501
502impl<Tz: TimeZone> Add<OldDuration> for Date<Tz> {
503    type Output = Date<Tz>;
504
505    #[inline]
506    fn add(self, rhs: OldDuration) -> Date<Tz> {
507        self.checked_add_signed(rhs).expect("`Date + Duration` overflowed")
508    }
509}
510
511impl<Tz: TimeZone> AddAssign<OldDuration> for Date<Tz> {
512    #[inline]
513    fn add_assign(&mut self, rhs: OldDuration) {
514        self.date = self.date.checked_add_signed(rhs).expect("`Date + Duration` overflowed");
515    }
516}
517
518impl<Tz: TimeZone> Sub<OldDuration> for Date<Tz> {
519    type Output = Date<Tz>;
520
521    #[inline]
522    fn sub(self, rhs: OldDuration) -> Date<Tz> {
523        self.checked_sub_signed(rhs).expect("`Date - Duration` overflowed")
524    }
525}
526
527impl<Tz: TimeZone> SubAssign<OldDuration> for Date<Tz> {
528    #[inline]
529    fn sub_assign(&mut self, rhs: OldDuration) {
530        self.date = self.date.checked_sub_signed(rhs).expect("`Date - Duration` overflowed");
531    }
532}
533
534impl<Tz: TimeZone> Sub<Date<Tz>> for Date<Tz> {
535    type Output = OldDuration;
536
537    #[inline]
538    fn sub(self, rhs: Date<Tz>) -> OldDuration {
539        self.signed_duration_since(rhs)
540    }
541}
542
543impl<Tz: TimeZone> fmt::Debug for Date<Tz> {
544    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
545        self.naive_local().fmt(f)?;
546        self.offset.fmt(f)
547    }
548}
549
550impl<Tz: TimeZone> fmt::Display for Date<Tz>
551where
552    Tz::Offset: fmt::Display,
553{
554    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
555        self.naive_local().fmt(f)?;
556        self.offset.fmt(f)
557    }
558}
559
560// Note that implementation of Arbitrary cannot be automatically derived for Date<Tz>, due to
561// the nontrivial bound <Tz as TimeZone>::Offset: Arbitrary.
562#[cfg(feature = "arbitrary")]
563impl<'a, Tz> arbitrary::Arbitrary<'a> for Date<Tz>
564where
565    Tz: TimeZone,
566    <Tz as TimeZone>::Offset: arbitrary::Arbitrary<'a>,
567{
568    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Date<Tz>> {
569        let date = NaiveDate::arbitrary(u)?;
570        let offset = <Tz as TimeZone>::Offset::arbitrary(u)?;
571        Ok(Date::from_utc(date, offset))
572    }
573}
574
575#[cfg(test)]
576mod tests {
577    use super::Date;
578
579    use crate::duration::Duration;
580    use crate::{FixedOffset, NaiveDate, Utc};
581
582    #[cfg(feature = "clock")]
583    use crate::offset::{Local, TimeZone};
584
585    #[test]
586    #[cfg(feature = "clock")]
587    fn test_years_elapsed() {
588        const WEEKS_PER_YEAR: f32 = 52.1775;
589
590        // This is always at least one year because 1 year = 52.1775 weeks.
591        let one_year_ago = Utc::today() - Duration::weeks((WEEKS_PER_YEAR * 1.5).ceil() as i64);
592        // A bit more than 2 years.
593        let two_year_ago = Utc::today() - Duration::weeks((WEEKS_PER_YEAR * 2.5).ceil() as i64);
594
595        assert_eq!(Utc::today().years_since(one_year_ago), Some(1));
596        assert_eq!(Utc::today().years_since(two_year_ago), Some(2));
597
598        // If the given DateTime is later than now, the function will always return 0.
599        let future = Utc::today() + Duration::weeks(12);
600        assert_eq!(Utc::today().years_since(future), None);
601    }
602
603    #[test]
604    fn test_date_add_assign() {
605        let naivedate = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
606        let date = Date::<Utc>::from_utc(naivedate, Utc);
607        let mut date_add = date;
608
609        date_add += Duration::days(5);
610        assert_eq!(date_add, date + Duration::days(5));
611
612        let timezone = FixedOffset::east_opt(60 * 60).unwrap();
613        let date = date.with_timezone(&timezone);
614        let date_add = date_add.with_timezone(&timezone);
615
616        assert_eq!(date_add, date + Duration::days(5));
617
618        let timezone = FixedOffset::west_opt(2 * 60 * 60).unwrap();
619        let date = date.with_timezone(&timezone);
620        let date_add = date_add.with_timezone(&timezone);
621
622        assert_eq!(date_add, date + Duration::days(5));
623    }
624
625    #[test]
626    #[cfg(feature = "clock")]
627    fn test_date_add_assign_local() {
628        let naivedate = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
629
630        let date = Local.from_utc_date(&naivedate);
631        let mut date_add = date;
632
633        date_add += Duration::days(5);
634        assert_eq!(date_add, date + Duration::days(5));
635    }
636
637    #[test]
638    fn test_date_sub_assign() {
639        let naivedate = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
640        let date = Date::<Utc>::from_utc(naivedate, Utc);
641        let mut date_sub = date;
642
643        date_sub -= Duration::days(5);
644        assert_eq!(date_sub, date - Duration::days(5));
645
646        let timezone = FixedOffset::east_opt(60 * 60).unwrap();
647        let date = date.with_timezone(&timezone);
648        let date_sub = date_sub.with_timezone(&timezone);
649
650        assert_eq!(date_sub, date - Duration::days(5));
651
652        let timezone = FixedOffset::west_opt(2 * 60 * 60).unwrap();
653        let date = date.with_timezone(&timezone);
654        let date_sub = date_sub.with_timezone(&timezone);
655
656        assert_eq!(date_sub, date - Duration::days(5));
657    }
658
659    #[test]
660    #[cfg(feature = "clock")]
661    fn test_date_sub_assign_local() {
662        let naivedate = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
663
664        let date = Local.from_utc_date(&naivedate);
665        let mut date_sub = date;
666
667        date_sub -= Duration::days(5);
668        assert_eq!(date_sub, date - Duration::days(5));
669    }
670}