1#![allow(deprecated)]
6
7#[cfg(feature = "alloc")]
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
16#[cfg(all(feature = "unstable-locales", feature = "alloc"))]
17use crate::format::Locale;
18#[cfg(feature = "alloc")]
19use crate::format::{DelayedFormat, Item, StrftimeItems};
20use crate::naive::{IsoWeek, NaiveDate, NaiveTime};
21use crate::offset::{TimeZone, Utc};
22use crate::{DateTime, Datelike, TimeDelta, Weekday};
23
24#[deprecated(since = "0.4.23", note = "Use `NaiveDate` or `DateTime<Tz>` instead")]
56#[derive(Clone)]
57#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
58pub struct Date<Tz: TimeZone> {
59 date: NaiveDate,
60 offset: Tz::Offset,
61}
62
63#[allow(deprecated)]
65#[deprecated(since = "0.4.20", note = "Use Date::MIN_UTC instead")]
66pub const MIN_DATE: Date<Utc> = Date::<Utc>::MIN_UTC;
67#[allow(deprecated)]
69#[deprecated(since = "0.4.20", note = "Use Date::MAX_UTC instead")]
70pub const MAX_DATE: Date<Utc> = Date::<Utc>::MAX_UTC;
71
72impl<Tz: TimeZone> Date<Tz> {
73 #[inline]
76 #[must_use]
77 pub fn from_utc(date: NaiveDate, offset: Tz::Offset) -> Date<Tz> {
78 Date { date, offset }
79 }
80
81 #[inline]
86 #[must_use]
87 pub fn and_time(&self, time: NaiveTime) -> Option<DateTime<Tz>> {
88 let localdt = self.naive_local().and_time(time);
89 self.timezone().from_local_datetime(&localdt).single()
90 }
91
92 #[deprecated(since = "0.4.23", note = "Use and_hms_opt() instead")]
97 #[inline]
98 #[must_use]
99 pub fn and_hms(&self, hour: u32, min: u32, sec: u32) -> DateTime<Tz> {
100 self.and_hms_opt(hour, min, sec).expect("invalid time")
101 }
102
103 #[inline]
108 #[must_use]
109 pub fn and_hms_opt(&self, hour: u32, min: u32, sec: u32) -> Option<DateTime<Tz>> {
110 NaiveTime::from_hms_opt(hour, min, sec).and_then(|time| self.and_time(time))
111 }
112
113 #[deprecated(since = "0.4.23", note = "Use and_hms_milli_opt() instead")]
119 #[inline]
120 #[must_use]
121 pub fn and_hms_milli(&self, hour: u32, min: u32, sec: u32, milli: u32) -> DateTime<Tz> {
122 self.and_hms_milli_opt(hour, min, sec, milli).expect("invalid time")
123 }
124
125 #[inline]
131 #[must_use]
132 pub fn and_hms_milli_opt(
133 &self,
134 hour: u32,
135 min: u32,
136 sec: u32,
137 milli: u32,
138 ) -> Option<DateTime<Tz>> {
139 NaiveTime::from_hms_milli_opt(hour, min, sec, milli).and_then(|time| self.and_time(time))
140 }
141
142 #[deprecated(since = "0.4.23", note = "Use and_hms_micro_opt() instead")]
148 #[inline]
149 #[must_use]
150 pub fn and_hms_micro(&self, hour: u32, min: u32, sec: u32, micro: u32) -> DateTime<Tz> {
151 self.and_hms_micro_opt(hour, min, sec, micro).expect("invalid time")
152 }
153
154 #[inline]
160 #[must_use]
161 pub fn and_hms_micro_opt(
162 &self,
163 hour: u32,
164 min: u32,
165 sec: u32,
166 micro: u32,
167 ) -> Option<DateTime<Tz>> {
168 NaiveTime::from_hms_micro_opt(hour, min, sec, micro).and_then(|time| self.and_time(time))
169 }
170
171 #[deprecated(since = "0.4.23", note = "Use and_hms_nano_opt() instead")]
177 #[inline]
178 #[must_use]
179 pub fn and_hms_nano(&self, hour: u32, min: u32, sec: u32, nano: u32) -> DateTime<Tz> {
180 self.and_hms_nano_opt(hour, min, sec, nano).expect("invalid time")
181 }
182
183 #[inline]
189 #[must_use]
190 pub fn and_hms_nano_opt(
191 &self,
192 hour: u32,
193 min: u32,
194 sec: u32,
195 nano: u32,
196 ) -> Option<DateTime<Tz>> {
197 NaiveTime::from_hms_nano_opt(hour, min, sec, nano).and_then(|time| self.and_time(time))
198 }
199
200 #[deprecated(since = "0.4.23", note = "Use succ_opt() instead")]
204 #[inline]
205 #[must_use]
206 pub fn succ(&self) -> Date<Tz> {
207 self.succ_opt().expect("out of bound")
208 }
209
210 #[inline]
214 #[must_use]
215 pub fn succ_opt(&self) -> Option<Date<Tz>> {
216 self.date.succ_opt().map(|date| Date::from_utc(date, self.offset.clone()))
217 }
218
219 #[deprecated(since = "0.4.23", note = "Use pred_opt() instead")]
223 #[inline]
224 #[must_use]
225 pub fn pred(&self) -> Date<Tz> {
226 self.pred_opt().expect("out of bound")
227 }
228
229 #[inline]
233 #[must_use]
234 pub fn pred_opt(&self) -> Option<Date<Tz>> {
235 self.date.pred_opt().map(|date| Date::from_utc(date, self.offset.clone()))
236 }
237
238 #[inline]
240 #[must_use]
241 pub fn offset(&self) -> &Tz::Offset {
242 &self.offset
243 }
244
245 #[inline]
247 #[must_use]
248 pub fn timezone(&self) -> Tz {
249 TimeZone::from_offset(&self.offset)
250 }
251
252 #[inline]
255 #[must_use]
256 pub fn with_timezone<Tz2: TimeZone>(&self, tz: &Tz2) -> Date<Tz2> {
257 tz.from_utc_date(&self.date)
258 }
259
260 #[inline]
264 #[must_use]
265 pub fn checked_add_signed(self, rhs: TimeDelta) -> Option<Date<Tz>> {
266 let date = self.date.checked_add_signed(rhs)?;
267 Some(Date { date, offset: self.offset })
268 }
269
270 #[inline]
274 #[must_use]
275 pub fn checked_sub_signed(self, rhs: TimeDelta) -> Option<Date<Tz>> {
276 let date = self.date.checked_sub_signed(rhs)?;
277 Some(Date { date, offset: self.offset })
278 }
279
280 #[inline]
286 #[must_use]
287 pub fn signed_duration_since<Tz2: TimeZone>(self, rhs: Date<Tz2>) -> TimeDelta {
288 self.date.signed_duration_since(rhs.date)
289 }
290
291 #[inline]
293 #[must_use]
294 pub fn naive_utc(&self) -> NaiveDate {
295 self.date
296 }
297
298 #[inline]
304 #[must_use]
305 pub fn naive_local(&self) -> NaiveDate {
306 self.date
307 }
308
309 #[must_use]
311 pub fn years_since(&self, base: Self) -> Option<u32> {
312 self.date.years_since(base.date)
313 }
314
315 pub const MIN_UTC: Date<Utc> = Date { date: NaiveDate::MIN, offset: Utc };
317 pub const MAX_UTC: Date<Utc> = Date { date: NaiveDate::MAX, offset: Utc };
319}
320
321fn map_local<Tz: TimeZone, F>(d: &Date<Tz>, mut f: F) -> Option<Date<Tz>>
323where
324 F: FnMut(NaiveDate) -> Option<NaiveDate>,
325{
326 f(d.naive_local()).and_then(|date| d.timezone().from_local_date(&date).single())
327}
328
329impl<Tz: TimeZone> Date<Tz>
330where
331 Tz::Offset: fmt::Display,
332{
333 #[cfg(feature = "alloc")]
335 #[inline]
336 #[must_use]
337 pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I>
338 where
339 I: Iterator<Item = B> + Clone,
340 B: Borrow<Item<'a>>,
341 {
342 DelayedFormat::new_with_offset(Some(self.naive_local()), None, &self.offset, items)
343 }
344
345 #[cfg(feature = "alloc")]
349 #[inline]
350 #[must_use]
351 pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>> {
352 self.format_with_items(StrftimeItems::new(fmt))
353 }
354
355 #[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 #[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
392impl<Tz: TimeZone> Datelike for Date<Tz> {
393 #[inline]
394 fn year(&self) -> i32 {
395 self.naive_local().year()
396 }
397 #[inline]
398 fn month(&self) -> u32 {
399 self.naive_local().month()
400 }
401 #[inline]
402 fn month0(&self) -> u32 {
403 self.naive_local().month0()
404 }
405 #[inline]
406 fn day(&self) -> u32 {
407 self.naive_local().day()
408 }
409 #[inline]
410 fn day0(&self) -> u32 {
411 self.naive_local().day0()
412 }
413 #[inline]
414 fn ordinal(&self) -> u32 {
415 self.naive_local().ordinal()
416 }
417 #[inline]
418 fn ordinal0(&self) -> u32 {
419 self.naive_local().ordinal0()
420 }
421 #[inline]
422 fn weekday(&self) -> Weekday {
423 self.naive_local().weekday()
424 }
425 #[inline]
426 fn iso_week(&self) -> IsoWeek {
427 self.naive_local().iso_week()
428 }
429
430 #[inline]
431 fn with_year(&self, year: i32) -> Option<Date<Tz>> {
432 map_local(self, |date| date.with_year(year))
433 }
434
435 #[inline]
436 fn with_month(&self, month: u32) -> Option<Date<Tz>> {
437 map_local(self, |date| date.with_month(month))
438 }
439
440 #[inline]
441 fn with_month0(&self, month0: u32) -> Option<Date<Tz>> {
442 map_local(self, |date| date.with_month0(month0))
443 }
444
445 #[inline]
446 fn with_day(&self, day: u32) -> Option<Date<Tz>> {
447 map_local(self, |date| date.with_day(day))
448 }
449
450 #[inline]
451 fn with_day0(&self, day0: u32) -> Option<Date<Tz>> {
452 map_local(self, |date| date.with_day0(day0))
453 }
454
455 #[inline]
456 fn with_ordinal(&self, ordinal: u32) -> Option<Date<Tz>> {
457 map_local(self, |date| date.with_ordinal(ordinal))
458 }
459
460 #[inline]
461 fn with_ordinal0(&self, ordinal0: u32) -> Option<Date<Tz>> {
462 map_local(self, |date| date.with_ordinal0(ordinal0))
463 }
464}
465
466impl<Tz: TimeZone> Copy for Date<Tz> where <Tz as TimeZone>::Offset: Copy {}
468unsafe impl<Tz: TimeZone> Send for Date<Tz> where <Tz as TimeZone>::Offset: Send {}
469
470impl<Tz: TimeZone, Tz2: TimeZone> PartialEq<Date<Tz2>> for Date<Tz> {
471 fn eq(&self, other: &Date<Tz2>) -> bool {
472 self.date == other.date
473 }
474}
475
476impl<Tz: TimeZone> Eq for Date<Tz> {}
477
478impl<Tz: TimeZone> PartialOrd for Date<Tz> {
479 fn partial_cmp(&self, other: &Date<Tz>) -> Option<Ordering> {
480 Some(self.cmp(other))
481 }
482}
483
484impl<Tz: TimeZone> Ord for Date<Tz> {
485 fn cmp(&self, other: &Date<Tz>) -> Ordering {
486 self.date.cmp(&other.date)
487 }
488}
489
490impl<Tz: TimeZone> hash::Hash for Date<Tz> {
491 fn hash<H: hash::Hasher>(&self, state: &mut H) {
492 self.date.hash(state)
493 }
494}
495
496impl<Tz: TimeZone> Add<TimeDelta> for Date<Tz> {
497 type Output = Date<Tz>;
498
499 #[inline]
500 fn add(self, rhs: TimeDelta) -> Date<Tz> {
501 self.checked_add_signed(rhs).expect("`Date + TimeDelta` overflowed")
502 }
503}
504
505impl<Tz: TimeZone> AddAssign<TimeDelta> for Date<Tz> {
506 #[inline]
507 fn add_assign(&mut self, rhs: TimeDelta) {
508 self.date = self.date.checked_add_signed(rhs).expect("`Date + TimeDelta` overflowed");
509 }
510}
511
512impl<Tz: TimeZone> Sub<TimeDelta> for Date<Tz> {
513 type Output = Date<Tz>;
514
515 #[inline]
516 fn sub(self, rhs: TimeDelta) -> Date<Tz> {
517 self.checked_sub_signed(rhs).expect("`Date - TimeDelta` overflowed")
518 }
519}
520
521impl<Tz: TimeZone> SubAssign<TimeDelta> for Date<Tz> {
522 #[inline]
523 fn sub_assign(&mut self, rhs: TimeDelta) {
524 self.date = self.date.checked_sub_signed(rhs).expect("`Date - TimeDelta` overflowed");
525 }
526}
527
528impl<Tz: TimeZone> Sub<Date<Tz>> for Date<Tz> {
529 type Output = TimeDelta;
530
531 #[inline]
532 fn sub(self, rhs: Date<Tz>) -> TimeDelta {
533 self.signed_duration_since(rhs)
534 }
535}
536
537impl<Tz: TimeZone> fmt::Debug for Date<Tz> {
538 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
539 self.naive_local().fmt(f)?;
540 self.offset.fmt(f)
541 }
542}
543
544impl<Tz: TimeZone> fmt::Display for Date<Tz>
545where
546 Tz::Offset: fmt::Display,
547{
548 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
549 self.naive_local().fmt(f)?;
550 self.offset.fmt(f)
551 }
552}
553
554#[cfg(all(feature = "arbitrary", feature = "std"))]
557impl<'a, Tz> arbitrary::Arbitrary<'a> for Date<Tz>
558where
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)]
570mod 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 let one_year_ago = Utc::today() - TimeDelta::weeks((WEEKS_PER_YEAR * 1.5).ceil() as i64);
585 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 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}