Coverage Report

Created: 2025-12-28 06:31

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