1#![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#[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#[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#[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 #[inline]
78 #[must_use]
79 pub fn from_utc(date: NaiveDate, offset: Tz::Offset) -> Date<Tz> {
80 Date { date, offset }
81 }
82
83 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[inline]
242 #[must_use]
243 pub fn offset(&self) -> &Tz::Offset {
244 &self.offset
245 }
246
247 #[inline]
249 #[must_use]
250 pub fn timezone(&self) -> Tz {
251 TimeZone::from_offset(&self.offset)
252 }
253
254 #[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 #[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 #[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 #[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 #[inline]
295 #[must_use]
296 pub fn naive_utc(&self) -> NaiveDate {
297 self.date
298 }
299
300 #[inline]
306 #[must_use]
307 pub fn naive_local(&self) -> NaiveDate {
308 self.date
309 }
310
311 #[must_use]
313 pub fn years_since(&self, base: Self) -> Option<u32> {
314 self.date.years_since(base.date)
315 }
316
317 pub const MIN_UTC: Date<Utc> = Date { date: NaiveDate::MIN, offset: Utc };
319 pub const MAX_UTC: Date<Utc> = Date { date: NaiveDate::MAX, offset: Utc };
321}
322
323fn 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 #[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 #[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 #[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 #[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
472impl<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#[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 let one_year_ago = Utc::today() - Duration::weeks((WEEKS_PER_YEAR * 1.5).ceil() as i64);
592 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 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}