-
Notifications
You must be signed in to change notification settings - Fork 545
/
Copy pathdate.rs
2766 lines (2538 loc) · 103 KB
/
date.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This is a part of Chrono.
// See README.md and LICENSE.txt for details.
//! ISO 8601 calendar date without timezone.
#[cfg(any(feature = "alloc", feature = "std", test))]
use core::borrow::Borrow;
use core::convert::TryFrom;
use core::ops::{Add, AddAssign, RangeInclusive, Sub, SubAssign};
use core::{fmt, str};
#[cfg(feature = "rkyv")]
use rkyv::{Archive, Deserialize, Serialize};
#[cfg(any(feature = "alloc", feature = "std", test))]
use crate::format::DelayedFormat;
use crate::format::{parse, ParseError, ParseResult, Parsed, StrftimeItems};
use crate::format::{Item, Numeric, Pad};
use crate::month::Months;
use crate::naive::{IsoWeek, NaiveDateTime, NaiveTime};
use crate::{Datelike, Month, TimeDelta, Weekday};
use super::internals::DateImpl;
use crate::{try_from_u64_to_i64, try_opt};
#[cfg(test)]
use super::internals;
// forces the cosnt validation
#[cfg(feature = "const-validation")]
#[macro_export]
/// a
macro_rules! ymd {
($y:expr, $m:expr, $d:expr) => {{
const _: NaiveDate = NaiveDate::from_ymd_validated($y, $m, $d);
NaiveDate::from_ymd_validated($y, $m, $d)
}};
}
// forces the cosnt validation
#[cfg(feature = "const-validation")]
#[macro_export]
/// a
macro_rules! yo {
($y:expr, $o:expr) => {{
const _: NaiveDate = NaiveDate::from_yo_validated($y, $o);
NaiveDate::from_yo_validated($y, $o)
}};
}
// MAX_YEAR-12-31 minus 0000-01-01
// = ((MAX_YEAR+1)-01-01 minus 0001-01-01) + (0001-01-01 minus 0000-01-01) - 1 day
// = ((MAX_YEAR+1)-01-01 minus 0001-01-01) + 365 days
// = MAX_YEAR * 365 + (# of leap years from 0001 to MAX_YEAR) + 365 days
#[cfg(test)] // only used for testing
const MAX_DAYS_FROM_YEAR_0: i32 = internals::MAX_YEAR as i32 * 365 + internals::MAX_YEAR as i32 / 4
- internals::MAX_YEAR as i32 / 100
+ internals::MAX_YEAR as i32 / 400
+ 365;
// MIN_YEAR-01-01 minus 0000-01-01
// = (MIN_YEAR+400n+1)-01-01 minus (400n+1)-01-01
// = ((MIN_YEAR+400n+1)-01-01 minus 0001-01-01) - ((400n+1)-01-01 minus 0001-01-01)
// = ((MIN_YEAR+400n+1)-01-01 minus 0001-01-01) - 146097n days
//
// n is set to 1000 for convenience.
#[cfg(test)] // only used for testing
const MIN_DAYS_FROM_YEAR_0: i32 = -MAX_DAYS_FROM_YEAR_0 - 1;
// (internals::MIN_YEAR as i32) * 365
// + (internals::MIN_YEAR as i32) / 4
// - (internals::MIN_YEAR as i32) / 100
// + (internals::MIN_YEAR as i32) / 400
// + 1;
#[cfg(test)] // only used for testing, but duplicated in naive::datetime
const MAX_BITS: usize = 44;
/// A week represented by a [`NaiveDate`] and a [`Weekday`] which is the first
/// day of the week.
#[derive(Debug)]
pub struct NaiveWeek {
date: NaiveDate,
start: Weekday,
}
impl NaiveWeek {
/// Returns a date representing the first day of the week.
///
/// # Examples
///
/// ```
/// use chrono::{NaiveDate, Weekday};
///
/// let date = NaiveDate::from_ymd_opt(2022, 4, 18).unwrap();
/// let week = date.week(Weekday::Mon);
/// assert!(week.first_day() <= date);
/// ```
#[inline]
pub fn first_day(&self) -> NaiveDate {
let start = self.start.num_days_from_monday();
let end = self.date.weekday().num_days_from_monday();
let days = if start > end { 7 - start + end } else { end - start };
self.date - TimeDelta::days(days.into())
}
/// Returns a date representing the last day of the week.
///
/// # Examples
///
/// ```
/// use chrono::{NaiveDate, Weekday};
///
/// let date = NaiveDate::from_ymd_opt(2022, 4, 18).unwrap();
/// let week = date.week(Weekday::Mon);
/// assert!(week.last_day() >= date);
/// ```
#[inline]
pub fn last_day(&self) -> NaiveDate {
self.first_day() + TimeDelta::days(6)
}
/// Returns a [`RangeInclusive<T>`] representing the whole week bounded by
/// [first_day](./struct.NaiveWeek.html#method.first_day) and
/// [last_day](./struct.NaiveWeek.html#method.last_day) functions.
///
/// # Examples
///
/// ```
/// use chrono::{NaiveDate, Weekday};
///
/// let date = NaiveDate::from_ymd_opt(2022, 4, 18).unwrap();
/// let week = date.week(Weekday::Mon);
/// let days = week.days();
/// assert!(days.contains(&date));
/// ```
#[inline]
pub fn days(&self) -> RangeInclusive<NaiveDate> {
self.first_day()..=self.last_day()
}
}
/// A duration in calendar days.
///
/// This is useful becuase when using `TimeDelta` it is possible
/// that adding `TimeDelta::days(1)` doesn't increment the day value as expected due to it being a
/// fixed number of seconds. This difference applies only when dealing with `DateTime<TimeZone>` data types
/// and in other cases `TimeDelta::days(n)` and `Days::new(n)` are equivalent.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct Days(pub(crate) u64);
impl Days {
/// Construct a new `Days` from a number of months
pub const fn new(num: u64) -> Self {
Self(num)
}
}
/// ISO 8601 calendar date without timezone.
/// Allows for every [proleptic Gregorian date](#calendar-date)
/// from Jan 1, 262145 BCE to Dec 31, 262143 CE.
/// Also supports the conversion from ISO 8601 ordinal and week date.
///
/// # Calendar Date
///
/// The ISO 8601 **calendar date** follows the proleptic Gregorian calendar.
/// It is like a normal civil calendar but note some slight differences:
///
/// * Dates before the Gregorian calendar's inception in 1582 are defined via the extrapolation.
/// Be careful, as historical dates are often noted in the Julian calendar and others
/// and the transition to Gregorian may differ across countries (as late as early 20C).
///
/// (Some example: Both Shakespeare from Britain and Cervantes from Spain seemingly died
/// on the same calendar date---April 23, 1616---but in the different calendar.
/// Britain used the Julian calendar at that time, so Shakespeare's death is later.)
///
/// * ISO 8601 calendars has the year 0, which is 1 BCE (a year before 1 CE).
/// If you need a typical BCE/BC and CE/AD notation for year numbers,
/// use the [`Datelike::year_ce`](../trait.Datelike.html#method.year_ce) method.
///
/// # Week Date
///
/// The ISO 8601 **week date** is a triple of year number, week number
/// and [day of the week](../enum.Weekday.html) with the following rules:
///
/// * A week consists of Monday through Sunday, and is always numbered within some year.
/// The week number ranges from 1 to 52 or 53 depending on the year.
///
/// * The week 1 of given year is defined as the first week containing January 4 of that year,
/// or equivalently, the first week containing four or more days in that year.
///
/// * The year number in the week date may *not* correspond to the actual Gregorian year.
/// For example, January 3, 2016 (Sunday) was on the last (53rd) week of 2015.
///
/// Chrono's date types default to the ISO 8601 [calendar date](#calendar-date),
/// but [`Datelike::iso_week`](../trait.Datelike.html#tymethod.iso_week) and
/// [`Datelike::weekday`](../trait.Datelike.html#tymethod.weekday) methods
/// can be used to get the corresponding week date.
///
/// # Ordinal Date
///
/// The ISO 8601 **ordinal date** is a pair of year number and day of the year ("ordinal").
/// The ordinal number ranges from 1 to 365 or 366 depending on the year.
/// The year number is the same as that of the [calendar date](#calendar-date).
///
/// This is currently the internal format of Chrono's date types.
#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Copy, Clone)]
#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
pub struct NaiveDate {
inner: DateImpl,
}
/// The minimum possible `NaiveDate` (January 1, -32769 BCE).
#[deprecated(since = "0.4.20", note = "Use NaiveDate::MIN instead")]
pub const MIN_DATE: NaiveDate = NaiveDate::MIN;
/// The maximum possible `NaiveDate` (December 31, 32767 CE).
#[deprecated(since = "0.4.20", note = "Use NaiveDate::MAX instead")]
pub const MAX_DATE: NaiveDate = NaiveDate::MAX;
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary<'_> for NaiveDate {
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<NaiveDate> {
Ok(NaiveDate { inner: arbitrary::Arbitrary::arbitrary(u)? })
}
}
// as it is hard to verify year flags in `NaiveDate::MIN` and `NaiveDate::MAX`,
// we use a separate run-time test.
#[test]
fn test_date_bounds() {
let calculated_min = NaiveDate::from_ymd_opt(internals::MIN_YEAR, 1, 1).unwrap();
let calculated_max = NaiveDate::from_ymd_opt(internals::MAX_YEAR, 12, 31).unwrap();
assert!(
NaiveDate::MIN == calculated_min,
"`NaiveDate::MIN` should have a year flag {:?}",
calculated_min.inner.year_type()
);
assert!(
NaiveDate::MAX == calculated_max,
"`NaiveDate::MAX` should have a year flag {:?}",
calculated_max.inner.year_type()
);
// let's also check that the entire range do not exceed 2^44 seconds
// (sometimes used for bounding `TimeDelta` against overflow)
let maxsecs = NaiveDate::MAX.signed_duration_since(NaiveDate::MIN).num_seconds();
let maxsecs = maxsecs + 86401; // also take care of DateTime
assert!(
maxsecs < (1 << MAX_BITS),
"The entire `NaiveDate` range somehow exceeds 2^{} seconds",
MAX_BITS
);
}
impl NaiveDate {
// /// Makes a new `NaiveDate` from year and packed ordinal-flags, with a verification.
// fn from_parts(year: i16, of: Of) -> Option<NaiveDate> {
// Some(NaiveDate { inner: DateImpl::from_parts(year, of)? })
// }
// /// Makes a new `NaiveDate` from year and packed month-day-flags, with a verification.
// fn from_mdf(year: i32, mdf: Mdf) -> Option<NaiveDate> {
// NaiveDate::from_parts(year, mdf.to_of()?)
// }
/// Makes a new `NaiveDate` from the [calendar date](#calendar-date)
/// (year, month and day).
///
/// Panics on the out-of-range date, invalid month and/or day.
#[deprecated(since = "0.4.23", note = "use `from_ymd_opt()` instead")]
pub fn from_ymd(year: i16, month: u8, day: u8) -> NaiveDate {
NaiveDate::from_ymd_opt(year, month, day).expect("invalid or out-of-range date")
}
/// Makes a new `NaiveDate` from the [calendar date](#calendar-date)
/// (year, month and day).
///
/// Returns `None` on the out-of-range date, invalid month and/or day.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
///
/// let from_ymd_opt = NaiveDate::from_ymd_opt;
///
/// assert!(from_ymd_opt(2015, 3, 14).is_some());
/// assert!(from_ymd_opt(2015, 0, 14).is_none());
/// assert!(from_ymd_opt(2015, 2, 29).is_none());
/// assert!(from_ymd_opt(-4, 2, 29).is_some()); // 5 BCE is a leap year
/// assert!(from_ymd_opt(400000, 1, 1).is_none());
/// assert!(from_ymd_opt(-400000, 1, 1).is_none());
/// ```
pub const fn from_ymd_opt(year: i16, month: u8, day: u8) -> Option<NaiveDate> {
Some(NaiveDate {
inner: try_opt!(DateImpl::from_ymd(year, try_opt!(Month::try_from_u8(month)), day)),
})
}
#[cfg(feature = "const-validation")]
///
pub const fn from_ymd_validated(year: i16, month: u8, day: u8) -> NaiveDate {
NaiveDate {
inner: DateImpl::from_ymd_validated(year, Month::try_from_u8_validated(month), day),
}
}
/// Makes a new `NaiveDate` from the [ordinal date](#ordinal-date)
/// (year and day of the year).
///
/// Panics on the out-of-range date and/or invalid day of year.
#[cfg(feature = "const-validation")]
pub const fn from_yo_validated(year: i16, ordinal: u16) -> NaiveDate {
NaiveDate { inner: DateImpl::from_yo_validated(year, ordinal) }
}
/// Makes a new `NaiveDate` from the [ordinal date](#ordinal-date)
/// (year and day of the year).
///
/// Returns `None` on the out-of-range date and/or invalid day of year.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
///
/// let from_yo_opt = NaiveDate::from_yo_opt;
///
/// assert!(from_yo_opt(2015, 100).is_some());
/// assert!(from_yo_opt(2015, 0).is_none());
/// assert!(from_yo_opt(2015, 365).is_some());
/// assert!(from_yo_opt(2015, 366).is_none());
/// assert!(from_yo_opt(-4, 366).is_some()); // 5 BCE is a leap year
/// assert!(from_yo_opt(400000, 1).is_none());
/// assert!(from_yo_opt(-400000, 1).is_none());
/// ```
pub const fn from_yo_opt(year: i16, ordinal: u16) -> Option<NaiveDate> {
Some(NaiveDate { inner: try_opt!(DateImpl::from_yo(year, ordinal)) })
}
/// Makes a new `NaiveDate` from the [ISO week date](#week-date)
/// (year, week number and day of the week).
/// The resulting `NaiveDate` may have a different year from the input year.
///
/// Panics on the out-of-range date and/or invalid week number.
#[deprecated(since = "0.4.23", note = "use `from_isoywd_opt()` instead")]
pub fn from_isoywd(year: i32, week: u16, weekday: Weekday) -> NaiveDate {
NaiveDate::from_isoywd_opt(year, week, weekday).expect("invalid or out-of-range date")
}
/// Makes a new `NaiveDate` from the [ISO week date](#week-date)
/// (year, week number and day of the week).
/// The resulting `NaiveDate` may have a different year from the input year.
///
/// Returns `None` on the out-of-range date and/or invalid week number.
///
/// # Example
///
/// ```
/// use chrono::{NaiveDate, Weekday};
///
/// let from_ymd = NaiveDate::from_ymd;
/// let from_isoywd_opt = NaiveDate::from_isoywd_opt;
///
/// assert_eq!(from_isoywd_opt(2015, 0, Weekday::Sun), None);
/// assert_eq!(from_isoywd_opt(2015, 10, Weekday::Sun), Some(from_ymd(2015, 3, 8)));
/// assert_eq!(from_isoywd_opt(2015, 30, Weekday::Mon), Some(from_ymd(2015, 7, 20)));
/// assert_eq!(from_isoywd_opt(2015, 60, Weekday::Mon), None);
///
/// assert_eq!(from_isoywd_opt(400000, 10, Weekday::Fri), None);
/// assert_eq!(from_isoywd_opt(-400000, 10, Weekday::Sat), None);
/// ```
///
/// The year number of ISO week date may differ from that of the calendar date.
///
/// ```
/// # use chrono::{NaiveDate, Weekday};
/// # let from_ymd = NaiveDate::from_ymd;
/// # let from_isoywd_opt = NaiveDate::from_isoywd_opt;
/// // Mo Tu We Th Fr Sa Su
/// // 2014-W52 22 23 24 25 26 27 28 has 4+ days of new year,
/// // 2015-W01 29 30 31 1 2 3 4 <- so this is the first week
/// assert_eq!(from_isoywd_opt(2014, 52, Weekday::Sun), Some(from_ymd(2014, 12, 28)));
/// assert_eq!(from_isoywd_opt(2014, 53, Weekday::Mon), None);
/// assert_eq!(from_isoywd_opt(2015, 1, Weekday::Mon), Some(from_ymd(2014, 12, 29)));
///
/// // 2015-W52 21 22 23 24 25 26 27 has 4+ days of old year,
/// // 2015-W53 28 29 30 31 1 2 3 <- so this is the last week
/// // 2016-W01 4 5 6 7 8 9 10
/// assert_eq!(from_isoywd_opt(2015, 52, Weekday::Sun), Some(from_ymd(2015, 12, 27)));
/// assert_eq!(from_isoywd_opt(2015, 53, Weekday::Sun), Some(from_ymd(2016, 1, 3)));
/// assert_eq!(from_isoywd_opt(2015, 54, Weekday::Mon), None);
/// assert_eq!(from_isoywd_opt(2016, 1, Weekday::Mon), Some(from_ymd(2016, 1, 4)));
/// ```
pub const fn from_isoywd_opt(year: i32, week: u16, weekday: Weekday) -> Option<NaiveDate> {
Some(NaiveDate { inner: try_opt!(DateImpl::from_isoywd_opt(year, week, weekday)) })
}
/// Makes a new `NaiveDate` from a day's number in the proleptic Gregorian calendar, with
/// January 1, 1 being day 1.
///
/// Panics if the date is out of range.
#[deprecated(since = "0.4.23", note = "use `from_num_days_from_ce_opt()` instead")]
#[inline]
pub fn from_num_days_from_ce(days: i32) -> NaiveDate {
NaiveDate::from_num_days_from_ce_opt(days).expect("out-of-range date")
}
/// Makes a new `NaiveDate` from a day's number in the proleptic Gregorian calendar, with
/// January 1, 1 being day 1.
///
/// Returns `None` if the date is out of range.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
///
/// let from_ndays_opt = NaiveDate::from_num_days_from_ce_opt;
/// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
///
/// assert_eq!(from_ndays_opt(730_000), Some(from_ymd(1999, 9, 3)));
/// assert_eq!(from_ndays_opt(1), Some(from_ymd(1, 1, 1)));
/// assert_eq!(from_ndays_opt(0), Some(from_ymd(0, 12, 31)));
/// assert_eq!(from_ndays_opt(-1), Some(from_ymd(0, 12, 30)));
/// assert_eq!(from_ndays_opt(100_000_000), None);
/// assert_eq!(from_ndays_opt(-100_000_000), None);
/// ```
pub const fn from_num_days_from_ce_opt(days: i32) -> Option<NaiveDate> {
Some(NaiveDate { inner: try_opt!(DateImpl::from_num_days_from_ce_opt(days)) })
}
/// Makes a new `NaiveDate` by counting the number of occurrences of a particular day-of-week
/// since the beginning of the given month. For instance, if you want the 2nd Friday of March
/// 2017, you would use `NaiveDate::from_weekday_of_month(2017, 3, Weekday::Fri, 2)`.
///
/// # Panics
///
/// The resulting `NaiveDate` is guaranteed to be in `month`. If `n` is larger than the number
/// of `weekday` in `month` (eg. the 6th Friday of March 2017) then this function will panic.
///
/// `n` is 1-indexed. Passing `n=0` will cause a panic.
#[deprecated(since = "0.4.23", note = "use `from_weekday_of_month_opt()` instead")]
pub fn from_weekday_of_month(year: i16, month: u8, weekday: Weekday, n: u8) -> NaiveDate {
NaiveDate::from_weekday_of_month_opt(year, month, weekday, n).expect("out-of-range date")
}
/// Makes a new `NaiveDate` by counting the number of occurrences of a particular day-of-week
/// since the beginning of the given month. For instance, if you want the 2nd Friday of March
/// 2017, you would use `NaiveDate::from_weekday_of_month(2017, 3, Weekday::Fri, 2)`. `n` is 1-indexed.
///
/// ```
/// use chrono::{NaiveDate, Weekday};
/// assert_eq!(NaiveDate::from_weekday_of_month_opt(2017, 3, Weekday::Fri, 2),
/// NaiveDate::from_ymd_opt(2017, 3, 10))
/// ```
///
/// Returns `None` if `n` out-of-range; ie. if `n` is larger than the number of `weekday` in
/// `month` (eg. the 6th Friday of March 2017), or if `n == 0`.
pub const fn from_weekday_of_month_opt(
year: i16,
month: u8,
weekday: Weekday,
n: u8,
) -> Option<NaiveDate> {
Some(NaiveDate {
inner: try_opt!(DateImpl::from_weekday_of_month_opt(
year,
try_opt!(Month::try_from_u8(month)),
weekday,
n,
)),
})
}
/// Parses a string with the specified format string and returns a new `NaiveDate`.
/// See the [`format::strftime` module](../format/strftime/index.html)
/// on the supported escape sequences.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
///
/// let parse_from_str = NaiveDate::parse_from_str;
///
/// assert_eq!(parse_from_str("2015-09-05", "%Y-%m-%d"),
/// Ok(NaiveDate::from_ymd_opt(2015, 9, 5).unwrap()));
/// assert_eq!(parse_from_str("5sep2015", "%d%b%Y"),
/// Ok(NaiveDate::from_ymd_opt(2015, 9, 5).unwrap()));
/// ```
///
/// Time and offset is ignored for the purpose of parsing.
///
/// ```
/// # use chrono::NaiveDate;
/// # let parse_from_str = NaiveDate::parse_from_str;
/// assert_eq!(parse_from_str("2014-5-17T12:34:56+09:30", "%Y-%m-%dT%H:%M:%S%z"),
/// Ok(NaiveDate::from_ymd_opt(2014, 5, 17).unwrap()));
/// ```
///
/// Out-of-bound dates or insufficient fields are errors.
///
/// ```
/// # use chrono::NaiveDate;
/// # let parse_from_str = NaiveDate::parse_from_str;
/// assert!(parse_from_str("2015/9", "%Y/%m").is_err());
/// assert!(parse_from_str("2015/9/31", "%Y/%m/%d").is_err());
/// ```
///
/// All parsed fields should be consistent to each other, otherwise it's an error.
///
/// ```
/// # use chrono::NaiveDate;
/// # let parse_from_str = NaiveDate::parse_from_str;
/// assert!(parse_from_str("Sat, 09 Aug 2013", "%a, %d %b %Y").is_err());
/// ```
pub fn parse_from_str(s: &str, fmt: &str) -> ParseResult<NaiveDate> {
let mut parsed = Parsed::new();
parse(&mut parsed, s, StrftimeItems::new(fmt))?;
parsed.to_naive_date()
}
/// Add a duration in [`Months`] to the date
///
/// If the day would be out of range for the resulting month, use the last day for that month.
///
/// Returns `None` if the resulting date would be out of range.
///
/// ```
/// # use chrono::{NaiveDate, Months};
/// assert_eq!(
/// NaiveDate::from_ymd_opt(2022, 2, 20).unwrap().checked_add_months(Months::new(6)),
/// Some(NaiveDate::from_ymd_opt(2022, 8, 20).unwrap())
/// );
/// assert_eq!(
/// NaiveDate::from_ymd_opt(2022, 7, 31).unwrap().checked_add_months(Months::new(2)),
/// Some(NaiveDate::from_ymd_opt(2022, 9, 30).unwrap())
/// );
/// ```
pub const fn checked_add_months(self, months: Months) -> Option<Self> {
if months.0 == 0 {
return Some(self);
}
match months.0 <= core::i32::MAX as u32 {
true => self.diff_months(months.0 as i32),
false => None,
}
}
/// Subtract a duration in [`Months`] from the date
///
/// If the day would be out of range for the resulting month, use the last day for that month.
///
/// Returns `None` if the resulting date would be out of range.
///
/// ```
/// # use chrono::{NaiveDate, Months};
/// assert_eq!(
/// NaiveDate::from_ymd_opt(2022, 2, 20).unwrap().checked_sub_months(Months::new(6)),
/// Some(NaiveDate::from_ymd_opt(2021, 8, 20).unwrap())
/// );
///
/// assert_eq!(
/// NaiveDate::from_ymd_opt(2014, 1, 1).unwrap()
/// .checked_sub_months(Months::new(core::i32::MAX as u32 + 1)),
/// None
/// );
/// ```
pub const fn checked_sub_months(self, months: Months) -> Option<Self> {
if months.0 == 0 {
return Some(self);
}
// Copy `i32::MAX` here so we don't have to do a complicated cast
match months.0 <= 2_147_483_647 {
true => self.diff_months(-(months.0 as i32)),
false => None,
}
}
const fn diff_months(self, months: i32) -> Option<Self> {
Some(NaiveDate { inner: try_opt!(self.inner.diff_months(months)) })
}
/// Add a duration in [`Days`] to the date
///
/// Returns `None` if the resulting date would be out of range.
///
/// ```
/// # use chrono::{NaiveDate, Days};
/// assert_eq!(
/// NaiveDate::from_ymd_opt(2022, 2, 20).unwrap().checked_add_days(Days::new(9)),
/// Some(NaiveDate::from_ymd_opt(2022, 3, 1).unwrap())
/// );
/// assert_eq!(
/// NaiveDate::from_ymd_opt(2022, 7, 31).unwrap().checked_add_days(Days::new(2)),
/// Some(NaiveDate::from_ymd_opt(2022, 8, 2).unwrap())
/// );
/// ```
pub const fn checked_add_days(self, days: Days) -> Option<Self> {
if days.0 == 0 {
return Some(self);
}
let days = try_from_u64_to_i64!(days.0);
self.diff_days(days)
}
/// Subtract a duration in [`Days`] from the date
///
/// Returns `None` if the resulting date would be out of range.
///
/// ```
/// # use chrono::{NaiveDate, Days};
/// assert_eq!(
/// NaiveDate::from_ymd_opt(2022, 2, 20).unwrap().checked_sub_days(Days::new(6)),
/// Some(NaiveDate::from_ymd_opt(2022, 2, 14).unwrap())
/// );
/// ```
pub const fn checked_sub_days(self, days: Days) -> Option<Self> {
if days.0 == 0 {
return Some(self);
}
let days = try_from_u64_to_i64!(days.0);
self.diff_days(-days)
}
const fn diff_days(self, days: i64) -> Option<Self> {
Some(NaiveDate { inner: try_opt!(self.inner.diff_days(days)) })
}
/// Makes a new `NaiveDateTime` from the current date and given `NaiveTime`.
///
/// # Example
///
/// ```
/// use chrono::{NaiveDate, NaiveTime, NaiveDateTime};
///
/// let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap();
/// let t = NaiveTime::from_hms_milli_opt(12, 34, 56, 789).unwrap();
///
/// let dt: NaiveDateTime = d.and_time(t);
/// assert_eq!(dt.date(), d);
/// assert_eq!(dt.time(), t);
/// ```
#[inline]
pub fn and_time(&self, time: NaiveTime) -> NaiveDateTime {
NaiveDateTime::new(*self, time)
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute and second.
///
/// No [leap second](./struct.NaiveTime.html#leap-second-handling) is allowed here;
/// use `NaiveDate::and_hms_*` methods with a subsecond parameter instead.
///
/// Panics on invalid hour, minute and/or second.
#[deprecated(since = "0.4.23", note = "use `and_hms_opt()` instead")]
#[inline]
pub fn and_hms(&self, hour: u32, min: u32, sec: u32) -> NaiveDateTime {
self.and_hms_opt(hour, min, sec).expect("invalid time")
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute and second.
///
/// No [leap second](./struct.NaiveTime.html#leap-second-handling) is allowed here;
/// use `NaiveDate::and_hms_*_opt` methods with a subsecond parameter instead.
///
/// Returns `None` on invalid hour, minute and/or second.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
///
/// let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap();
/// assert!(d.and_hms_opt(12, 34, 56).is_some());
/// assert!(d.and_hms_opt(12, 34, 60).is_none()); // use `and_hms_milli_opt` instead
/// assert!(d.and_hms_opt(12, 60, 56).is_none());
/// assert!(d.and_hms_opt(24, 34, 56).is_none());
/// ```
#[inline]
pub fn and_hms_opt(&self, hour: u32, min: u32, sec: u32) -> Option<NaiveDateTime> {
NaiveTime::from_hms_opt(hour, min, sec).map(|time| self.and_time(time))
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and millisecond.
///
/// The millisecond part can exceed 1,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Panics on invalid hour, minute, second and/or millisecond.
#[deprecated(since = "0.4.23", note = "use `and_hms_milli_opt()` instead")]
#[inline]
pub fn and_hms_milli(&self, hour: u32, min: u32, sec: u32, milli: u32) -> NaiveDateTime {
self.and_hms_milli_opt(hour, min, sec, milli).expect("invalid time")
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and millisecond.
///
/// The millisecond part can exceed 1,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Returns `None` on invalid hour, minute, second and/or millisecond.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
///
/// let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap();
/// assert!(d.and_hms_milli_opt(12, 34, 56, 789).is_some());
/// assert!(d.and_hms_milli_opt(12, 34, 59, 1_789).is_some()); // leap second
/// assert!(d.and_hms_milli_opt(12, 34, 59, 2_789).is_none());
/// assert!(d.and_hms_milli_opt(12, 34, 60, 789).is_none());
/// assert!(d.and_hms_milli_opt(12, 60, 56, 789).is_none());
/// assert!(d.and_hms_milli_opt(24, 34, 56, 789).is_none());
/// ```
#[inline]
pub fn and_hms_milli_opt(
&self,
hour: u32,
min: u32,
sec: u32,
milli: u32,
) -> Option<NaiveDateTime> {
NaiveTime::from_hms_milli_opt(hour, min, sec, milli).map(|time| self.and_time(time))
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and microsecond.
///
/// The microsecond part can exceed 1,000,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Panics on invalid hour, minute, second and/or microsecond.
///
/// # Example
///
/// ```
/// use chrono::{NaiveDate, NaiveDateTime, Datelike, Timelike, Weekday};
///
/// let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap();
///
/// let dt: NaiveDateTime = d.and_hms_micro(12, 34, 56, 789_012);
/// assert_eq!(dt.year(), 2015);
/// assert_eq!(dt.weekday(), Weekday::Wed);
/// assert_eq!(dt.second(), 56);
/// assert_eq!(dt.nanosecond(), 789_012_000);
/// ```
#[deprecated(since = "0.4.23", note = "use `and_hms_micro_opt()` instead")]
#[inline]
pub fn and_hms_micro(&self, hour: u32, min: u32, sec: u32, micro: u32) -> NaiveDateTime {
self.and_hms_micro_opt(hour, min, sec, micro).expect("invalid time")
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and microsecond.
///
/// The microsecond part can exceed 1,000,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Returns `None` on invalid hour, minute, second and/or microsecond.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
///
/// let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap();
/// assert!(d.and_hms_micro_opt(12, 34, 56, 789_012).is_some());
/// assert!(d.and_hms_micro_opt(12, 34, 59, 1_789_012).is_some()); // leap second
/// assert!(d.and_hms_micro_opt(12, 34, 59, 2_789_012).is_none());
/// assert!(d.and_hms_micro_opt(12, 34, 60, 789_012).is_none());
/// assert!(d.and_hms_micro_opt(12, 60, 56, 789_012).is_none());
/// assert!(d.and_hms_micro_opt(24, 34, 56, 789_012).is_none());
/// ```
#[inline]
pub fn and_hms_micro_opt(
&self,
hour: u32,
min: u32,
sec: u32,
micro: u32,
) -> Option<NaiveDateTime> {
NaiveTime::from_hms_micro_opt(hour, min, sec, micro).map(|time| self.and_time(time))
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and nanosecond.
///
/// The nanosecond part can exceed 1,000,000,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Panics on invalid hour, minute, second and/or nanosecond.
#[deprecated(since = "0.4.23", note = "use `and_hms_nano_opt()` instead")]
#[inline]
pub fn and_hms_nano(&self, hour: u32, min: u32, sec: u32, nano: u32) -> NaiveDateTime {
self.and_hms_nano_opt(hour, min, sec, nano).expect("invalid time")
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and nanosecond.
///
/// The nanosecond part can exceed 1,000,000,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Returns `None` on invalid hour, minute, second and/or nanosecond.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
///
/// let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap();
/// assert!(d.and_hms_nano_opt(12, 34, 56, 789_012_345).is_some());
/// assert!(d.and_hms_nano_opt(12, 34, 59, 1_789_012_345).is_some()); // leap second
/// assert!(d.and_hms_nano_opt(12, 34, 59, 2_789_012_345).is_none());
/// assert!(d.and_hms_nano_opt(12, 34, 60, 789_012_345).is_none());
/// assert!(d.and_hms_nano_opt(12, 60, 56, 789_012_345).is_none());
/// assert!(d.and_hms_nano_opt(24, 34, 56, 789_012_345).is_none());
/// ```
#[inline]
pub fn and_hms_nano_opt(
&self,
hour: u32,
min: u32,
sec: u32,
nano: u32,
) -> Option<NaiveDateTime> {
NaiveTime::from_hms_nano_opt(hour, min, sec, nano).map(|time| self.and_time(time))
}
// /// Returns the packed month-day-flags.
// #[inline]
// fn mdf(&self) -> Mdf {
// self.of().to_mdf()
// }
// /// Returns the packed ordinal-flags.
// #[inline]
// fn of(&self) -> Of {
// self.inner.of()
// }
// /// Makes a new `NaiveDate` with the packed month-day-flags changed.
// ///
// /// Returns `None` when the resulting `NaiveDate` would be invalid.
// #[inline]
// fn with_mdf(&self, mdf: Mdf) -> Option<NaiveDate> {
// self.with_of(mdf.to_of()?)
// }
// /// Makes a new `NaiveDate` with the packed ordinal-flags changed.
// ///
// /// Returns `None` when the resulting `NaiveDate` would be invalid.
// #[inline]
// fn with_of(&self, of: Of) -> Option<NaiveDate> {
// Some(NaiveDate { inner: DateImpl::from_parts(self.year(), of)? })
// }
/// Makes a new `NaiveDate` for the next calendar date.
///
/// Panics when `self` is the last representable date.
#[deprecated(since = "0.4.23", note = "use `succ_opt()` instead")]
#[inline]
pub fn succ(&self) -> NaiveDate {
self.succ_opt().expect("out of bound")
}
/// Makes a new `NaiveDate` for the next calendar date.
///
/// Returns `None` when `self` is the last representable date.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
///
/// assert_eq!(NaiveDate::from_ymd_opt(2015, 6, 3).unwrap().succ_opt(),
/// Some(NaiveDate::from_ymd_opt(2015, 6, 4).unwrap()));
/// assert_eq!(NaiveDate::MAX.succ_opt(), None);
/// ```
#[inline]
pub const fn succ_opt(&self) -> Option<NaiveDate> {
Some(NaiveDate { inner: try_opt!(self.inner.succ_opt()) })
}
/// Makes a new `NaiveDate` for the previous calendar date.
///
/// Panics when `self` is the first representable date.
#[deprecated(since = "0.4.23", note = "use `pred_opt()` instead")]
#[inline]
pub fn pred(&self) -> NaiveDate {
self.pred_opt().expect("out of bound")
}
/// Makes a new `NaiveDate` for the previous calendar date.
///
/// Returns `None` when `self` is the first representable date.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
///
/// assert_eq!(NaiveDate::from_ymd_opt(2015, 6, 3).unwrap().pred_opt(),
/// Some(NaiveDate::from_ymd_opt(2015, 6, 2).unwrap()));
/// assert_eq!(NaiveDate::MIN.pred_opt(), None);
/// ```
#[inline]
pub const fn pred_opt(&self) -> Option<NaiveDate> {
Some(NaiveDate { inner: try_opt!(self.inner.pred_opt()) })
}
/// Subtracts another `NaiveDate` from the current date.
/// Returns a `TimeDelta` of integral numbers.
///
/// This does not overflow or underflow at all,
/// as all possible output fits in the range of `TimeDelta`.
///
/// # Example
///
/// ```
/// use chrono::{TimeDelta, NaiveDate};
///
/// let from_ymd = NaiveDate::from_ymd;
/// let since = NaiveDate::signed_duration_since;
///
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2014, 1, 1)), TimeDelta::zero());
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2013, 12, 31)), TimeDelta::days(1));
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2014, 1, 2)), TimeDelta::days(-1));
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2013, 9, 23)), TimeDelta::days(100));
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2013, 1, 1)), TimeDelta::days(365));
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2010, 1, 1)), TimeDelta::days(365*4 + 1));
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(1614, 1, 1)), TimeDelta::days(365*400 + 97));
/// ```
pub fn signed_duration_since(self, rhs: NaiveDate) -> TimeDelta {
TimeDelta::days(self.inner.signed_duration_since(rhs.inner))
}
///
///
pub fn checked_add_signed(self, rhs: TimeDelta) -> Option<Self> {
Some(NaiveDate { inner: self.inner.checked_add_signed(rhs.num_days())? })
}
///
///
pub fn checked_sub_signed(self, rhs: TimeDelta) -> Option<Self> {
Some(NaiveDate { inner: self.inner.checked_sub_signed(rhs.num_days())? })
}
/// Formats the date with the specified formatting items.
/// Otherwise it is the same as the ordinary `format` method.
///
/// The `Iterator` of items should be `Clone`able,
/// since the resulting `DelayedFormat` value may be formatted multiple times.
///
/// # Example
///
/// ```
/// use chrono::NaiveDate;
/// use chrono::format::strftime::StrftimeItems;
///
/// let fmt = StrftimeItems::new("%Y-%m-%d");
/// let d = NaiveDate::from_ymd_opt(2015, 9, 5).unwrap();
/// assert_eq!(d.format_with_items(fmt.clone()).to_string(), "2015-09-05");
/// assert_eq!(d.format("%Y-%m-%d").to_string(), "2015-09-05");
/// ```
///
/// The resulting `DelayedFormat` can be formatted directly via the `Display` trait.
///
/// ```
/// # use chrono::NaiveDate;
/// # use chrono::format::strftime::StrftimeItems;
/// # let fmt = StrftimeItems::new("%Y-%m-%d").clone();
/// # let d = NaiveDate::from_ymd_opt(2015, 9, 5).unwrap();
/// assert_eq!(format!("{}", d.format_with_items(fmt)), "2015-09-05");
/// ```
#[cfg(any(feature = "alloc", feature = "std", test))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "alloc", feature = "std"))))]
#[inline]
pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I>
where
I: Iterator<Item = B> + Clone,
B: Borrow<Item<'a>>,
{
DelayedFormat::new(Some(*self), None, items)
}
/// Formats the date with the specified format string.
/// See the [`format::strftime` module](../format/strftime/index.html)
/// on the supported escape sequences.
///
/// This returns a `DelayedFormat`,
/// which gets converted to a string only when actual formatting happens.
/// You may use the `to_string` method to get a `String`,
/// or just feed it into `print!` and other formatting macros.
/// (In this way it avoids the redundant memory allocation.)