forked from chronotope/chrono
-
Notifications
You must be signed in to change notification settings - Fork 1
/
date.rs
3259 lines (3002 loc) · 119 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"))]
use core::borrow::Borrow;
use core::iter::FusedIterator;
use core::ops::{Add, AddAssign, RangeInclusive, Sub, SubAssign};
use core::{fmt, str};
#[cfg(feature = "rkyv")]
use rkyv::{Archive, Deserialize, Serialize};
/// L10n locales.
#[cfg(feature = "unstable-locales")]
use pure_rust_locales::Locale;
use crate::duration::Duration as OldDuration;
#[cfg(any(feature = "alloc", feature = "std"))]
use crate::format::DelayedFormat;
use crate::format::{
parse, parse_and_remainder, write_hundreds, Item, Numeric, Pad, ParseError, ParseResult,
Parsed, StrftimeItems,
};
use crate::month::Months;
use crate::naive::{IsoWeek, NaiveDateTime, NaiveTime};
use crate::{expect, try_opt};
use crate::{Datelike, Weekday};
use super::internals::{self, DateImpl, Mdf, Of, YearFlags};
use super::isoweek;
const MAX_YEAR: i32 = internals::MAX_YEAR;
const MIN_YEAR: i32 = internals::MIN_YEAR;
/// 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.
///
/// # Panics
///
/// Panics if the first day of the week happens to fall just out of range of `NaiveDate`
/// (more than ca. 262,000 years away from common era).
///
/// # 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]
#[must_use]
pub fn first_day(&self) -> NaiveDate {
let start = self.start.num_days_from_monday() as i32;
let ref_day = self.date.weekday().num_days_from_monday() as i32;
// Calculate the number of days to subtract from `self.date`.
// Do not construct an intermediate date beyond `self.date`, because that may be out of
// range if `date` is close to `NaiveDate::MAX`.
let days = start - ref_day - if start > ref_day { 7 } else { 0 };
self.date.add_days(days).unwrap()
}
/// Returns a date representing the last day of the week.
///
/// # Panics
///
/// Panics if the last day of the week happens to fall just out of range of `NaiveDate`
/// (more than ca. 262,000 years away from common era).
///
/// # 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]
#[must_use]
pub fn last_day(&self) -> NaiveDate {
let end = self.start.pred().num_days_from_monday() as i32;
let ref_day = self.date.weekday().num_days_from_monday() as i32;
// Calculate the number of days to add to `self.date`.
// Do not construct an intermediate date before `self.date` (like with `first_day()`),
// because that may be out of range if `date` is close to `NaiveDate::MIN`.
let days = end - ref_day + if end < ref_day { 7 } else { 0 };
self.date.add_days(days).unwrap()
}
/// 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.
///
/// # Panics
///
/// Panics if the either the first or last day of the week happens to fall just out of range of
/// `NaiveDate` (more than ca. 262,000 years away from common era).
///
/// # 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]
#[must_use]
pub fn days(&self) -> RangeInclusive<NaiveDate> {
self.first_day()..=self.last_day()
}
}
/// A duration in calendar days.
///
/// This is useful because when using `Duration` it is possible
/// that adding `Duration::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 `Duration::days(n)` and `Days::new(n)` are equivalent.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct Days(pub(crate) u64);
impl Days {
/// Construct a new `Days` from a number of days
pub const fn new(num: u64) -> Self {
Self(num)
}
}
/// ISO 8601 calendar date without timezone.
/// Allows for every [proleptic Gregorian 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.
///
/// [proleptic Gregorian date]: crate::NaiveDate#calendar-date
#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Copy, Clone)]
#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
pub struct NaiveDate {
ymdf: DateImpl, // (year << 13) | of
}
/// The minimum possible `NaiveDate` (January 1, 262145 BCE).
#[deprecated(since = "0.4.20", note = "Use NaiveDate::MIN instead")]
pub const MIN_DATE: NaiveDate = NaiveDate::MIN;
/// The maximum possible `NaiveDate` (December 31, 262143 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> {
let year = u.int_in_range(MIN_YEAR..=MAX_YEAR)?;
let max_days = YearFlags::from_year(year).ndays();
let ord = u.int_in_range(1..=max_days)?;
NaiveDate::from_yo_opt(year, ord).ok_or(arbitrary::Error::IncorrectFormat)
}
}
impl NaiveDate {
pub(crate) fn weeks_from(&self, day: Weekday) -> i32 {
(self.ordinal() as i32 - self.weekday().num_days_from(day) as i32 + 6) / 7
}
/// Makes a new `NaiveDate` from year, ordinal and flags.
/// Does not check whether the flags are correct for the provided year.
const fn from_ordinal_and_flags(
year: i32,
ordinal: u32,
flags: YearFlags,
) -> Option<NaiveDate> {
if year < MIN_YEAR || year > MAX_YEAR {
return None; // Out-of-range
}
debug_assert!(YearFlags::from_year(year).0 == flags.0);
match Of::new(ordinal, flags) {
Some(of) => Some(NaiveDate { ymdf: (year << 13) | (of.inner() as DateImpl) }),
None => None, // Invalid: Ordinal outside of the nr of days in a year with those flags.
}
}
/// Makes a new `NaiveDate` from year and packed month-day-flags.
/// Does not check whether the flags are correct for the provided year.
const fn from_mdf(year: i32, mdf: Mdf) -> Option<NaiveDate> {
if year < MIN_YEAR || year > MAX_YEAR {
return None; // Out-of-range
}
match mdf.to_of() {
Some(of) => Some(NaiveDate { ymdf: (year << 13) | (of.inner() as DateImpl) }),
None => None, // Non-existing date
}
}
/// Makes a new `NaiveDate` from the [calendar date](#calendar-date)
/// (year, month and day).
///
/// # Panics
///
/// Panics if the specified calendar day does not exist, on invalid values for `month` or `day`,
/// or if `year` is out of range for `NaiveDate`.
#[deprecated(since = "0.4.23", note = "use `from_ymd_opt()` instead")]
#[must_use]
pub const fn from_ymd(year: i32, month: u32, day: u32) -> NaiveDate {
expect!(NaiveDate::from_ymd_opt(year, month, day), "invalid or out-of-range date")
}
/// Makes a new `NaiveDate` from the [calendar date](#calendar-date)
/// (year, month and day).
///
/// # Errors
///
/// Returns `None` if:
/// - The specified calendar day does not exist (for example 2023-04-31).
/// - The value for `month` or `day` is invalid.
/// - `year` is out of range for `NaiveDate`.
///
/// # 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());
/// ```
#[must_use]
pub const fn from_ymd_opt(year: i32, month: u32, day: u32) -> Option<NaiveDate> {
let flags = YearFlags::from_year(year);
if let Some(mdf) = Mdf::new(month, day, flags) {
NaiveDate::from_mdf(year, mdf)
} else {
None
}
}
/// Makes a new `NaiveDate` from the [ordinal date](#ordinal-date)
/// (year and day of the year).
///
/// # Panics
///
/// Panics if the specified ordinal day does not exist, on invalid values for `ordinal`, or if
/// `year` is out of range for `NaiveDate`.
#[deprecated(since = "0.4.23", note = "use `from_yo_opt()` instead")]
#[must_use]
pub const fn from_yo(year: i32, ordinal: u32) -> NaiveDate {
expect!(NaiveDate::from_yo_opt(year, ordinal), "invalid or out-of-range date")
}
/// Makes a new `NaiveDate` from the [ordinal date](#ordinal-date)
/// (year and day of the year).
///
/// # Errors
///
/// Returns `None` if:
/// - The specified ordinal day does not exist (for example 2023-366).
/// - The value for `ordinal` is invalid (for example: `0`, `400`).
/// - `year` is out of range for `NaiveDate`.
///
/// # 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());
/// ```
#[must_use]
pub const fn from_yo_opt(year: i32, ordinal: u32) -> Option<NaiveDate> {
let flags = YearFlags::from_year(year);
NaiveDate::from_ordinal_and_flags(year, ordinal, flags)
}
/// 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
///
/// Panics if the specified week does not exist in that year, on invalid values for `week`, or
/// if the resulting date is out of range for `NaiveDate`.
#[deprecated(since = "0.4.23", note = "use `from_isoywd_opt()` instead")]
#[must_use]
pub const fn from_isoywd(year: i32, week: u32, weekday: Weekday) -> NaiveDate {
expect!(NaiveDate::from_isoywd_opt(year, week, weekday), "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.
///
/// # Errors
///
/// Returns `None` if:
/// - The specified week does not exist in that year (for example 2023 week 53).
/// - The value for `week` is invalid (for example: `0`, `60`).
/// - If the resulting date is out of range for `NaiveDate`.
///
/// # Example
///
/// ```
/// use chrono::{NaiveDate, Weekday};
///
/// let from_ymd = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
/// 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 = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).unwrap();
/// # 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)));
/// ```
#[must_use]
pub const fn from_isoywd_opt(year: i32, week: u32, weekday: Weekday) -> Option<NaiveDate> {
let flags = YearFlags::from_year(year);
let nweeks = flags.nisoweeks();
if 1 <= week && week <= nweeks {
// ordinal = week ordinal - delta
let weekord = week * 7 + weekday as u32;
let delta = flags.isoweek_delta();
if weekord <= delta {
// ordinal < 1, previous year
let prevflags = YearFlags::from_year(year - 1);
NaiveDate::from_ordinal_and_flags(
year - 1,
weekord + prevflags.ndays() - delta,
prevflags,
)
} else {
let ordinal = weekord - delta;
let ndays = flags.ndays();
if ordinal <= ndays {
// this year
NaiveDate::from_ordinal_and_flags(year, ordinal, flags)
} else {
// ordinal > ndays, next year
let nextflags = YearFlags::from_year(year + 1);
NaiveDate::from_ordinal_and_flags(year + 1, ordinal - ndays, nextflags)
}
}
} else {
None
}
}
/// Makes a new `NaiveDate` from a day's number in the proleptic Gregorian calendar, with
/// January 1, 1 being day 1.
///
/// # Panics
///
/// Panics if the date is out of range.
#[deprecated(since = "0.4.23", note = "use `from_num_days_from_ce_opt()` instead")]
#[inline]
#[must_use]
pub const fn from_num_days_from_ce(days: i32) -> NaiveDate {
expect!(NaiveDate::from_num_days_from_ce_opt(days), "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.
///
/// # Errors
///
/// 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);
/// ```
#[must_use]
pub const fn from_num_days_from_ce_opt(days: i32) -> Option<NaiveDate> {
let days = try_opt!(days.checked_add(365)); // make December 31, 1 BCE equal to day 0
let year_div_400 = days.div_euclid(146_097);
let cycle = days.rem_euclid(146_097);
let (year_mod_400, ordinal) = internals::cycle_to_yo(cycle as u32);
let flags = YearFlags::from_year_mod_400(year_mod_400 as i32);
NaiveDate::from_ordinal_and_flags(year_div_400 * 400 + year_mod_400 as i32, ordinal, flags)
}
/// 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.
///
/// # Panics
///
/// Panics if the specified day does not exist in that month, on invalid values for `month` or
/// `n`, or if `year` is out of range for `NaiveDate`.
#[deprecated(since = "0.4.23", note = "use `from_weekday_of_month_opt()` instead")]
#[must_use]
pub const fn from_weekday_of_month(
year: i32,
month: u32,
weekday: Weekday,
n: u8,
) -> NaiveDate {
expect!(NaiveDate::from_weekday_of_month_opt(year, month, weekday, n), "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.
///
/// # Errors
///
/// Returns `None` if:
/// - The specified day does not exist in that month (for example the 5th Monday of Apr. 2023).
/// - The value for `month` or `n` is invalid.
/// - `year` is out of range for `NaiveDate`.
///
/// # Example
///
/// ```
/// use chrono::{NaiveDate, Weekday};
/// assert_eq!(NaiveDate::from_weekday_of_month_opt(2017, 3, Weekday::Fri, 2),
/// NaiveDate::from_ymd_opt(2017, 3, 10))
/// ```
#[must_use]
pub const fn from_weekday_of_month_opt(
year: i32,
month: u32,
weekday: Weekday,
n: u8,
) -> Option<NaiveDate> {
if n == 0 {
return None;
}
let first = try_opt!(NaiveDate::from_ymd_opt(year, month, 1)).weekday();
let first_to_dow = (7 + weekday.number_from_monday() - first.number_from_monday()) % 7;
let day = (n - 1) as u32 * 7 + first_to_dow + 1;
NaiveDate::from_ymd_opt(year, month, day)
}
/// 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()
}
/// Parses a string from a user-specified format into a new `NaiveDate` value, and a slice with
/// the remaining portion of the string.
/// See the [`format::strftime` module](../format/strftime/index.html)
/// on the supported escape sequences.
///
/// Similar to [`parse_from_str`](#method.parse_from_str).
///
/// # Example
///
/// ```rust
/// # use chrono::{NaiveDate};
/// let (date, remainder) = NaiveDate::parse_and_remainder(
/// "2015-02-18 trailing text", "%Y-%m-%d").unwrap();
/// assert_eq!(date, NaiveDate::from_ymd_opt(2015, 2, 18).unwrap());
/// assert_eq!(remainder, " trailing text");
/// ```
pub fn parse_and_remainder<'a>(s: &'a str, fmt: &str) -> ParseResult<(NaiveDate, &'a str)> {
let mut parsed = Parsed::new();
let remainder = parse_and_remainder(&mut parsed, s, StrftimeItems::new(fmt))?;
parsed.to_naive_date().map(|d| (d, remainder))
}
/// Add a duration in [`Months`] to the date
///
/// Uses the last day of the month if the day does not exist in the resulting month.
///
/// # Errors
///
/// Returns `None` if the resulting date would be out of range.
///
/// # Example
///
/// ```
/// # 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())
/// );
/// ```
#[must_use]
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
///
/// Uses the last day of the month if the day does not exist in the resulting month.
///
/// # Errors
///
/// Returns `None` if the resulting date would be out of range.
///
/// # Example
///
/// ```
/// # 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
/// );
/// ```
#[must_use]
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> {
let (years, left) = ((months / 12), (months % 12));
// Determine new year (without taking months into account for now
let year = if (years > 0 && years > (MAX_YEAR - self.year()))
|| (years < 0 && years < (MIN_YEAR - self.year()))
{
return None;
} else {
self.year() + years
};
// Determine new month
let month = self.month() as i32 + left;
let (year, month) = if month <= 0 {
if year == MIN_YEAR {
return None;
}
(year - 1, month + 12)
} else if month > 12 {
if year == MAX_YEAR {
return None;
}
(year + 1, month - 12)
} else {
(year, month)
};
// Clamp original day in case new month is shorter
let flags = YearFlags::from_year(year);
let feb_days = if flags.ndays() == 366 { 29 } else { 28 };
let days = [31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let day_max = days[(month - 1) as usize];
let mut day = self.day();
if day > day_max {
day = day_max;
};
NaiveDate::from_mdf(year, try_opt!(Mdf::new(month as u32, day, flags)))
}
/// Add a duration in [`Days`] to the date
///
/// # Errors
///
/// Returns `None` if the resulting date would be out of range.
///
/// # Example
///
/// ```
/// # 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())
/// );
/// assert_eq!(
/// NaiveDate::from_ymd_opt(2022, 7, 31).unwrap().checked_add_days(Days::new(1000000000000)),
/// None
/// );
/// ```
#[must_use]
pub const fn checked_add_days(self, days: Days) -> Option<Self> {
match days.0 <= i32::MAX as u64 {
true => self.add_days(days.0 as i32),
false => None,
}
}
/// Subtract a duration in [`Days`] from the date
///
/// # Errors
///
/// Returns `None` if the resulting date would be out of range.
///
/// # Example
///
/// ```
/// # 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())
/// );
/// assert_eq!(
/// NaiveDate::from_ymd_opt(2022, 2, 20).unwrap().checked_sub_days(Days::new(1000000000000)),
/// None
/// );
/// ```
#[must_use]
pub const fn checked_sub_days(self, days: Days) -> Option<Self> {
match days.0 <= i32::MAX as u64 {
true => self.add_days(-(days.0 as i32)),
false => None,
}
}
/// Add a duration of `i32` days to the date.
pub(crate) const fn add_days(self, days: i32) -> Option<Self> {
// fast path if the result is within the same year
const ORDINAL_MASK: i32 = 0b1_1111_1111_0000;
if let Some(ordinal) = ((self.ymdf & ORDINAL_MASK) >> 4).checked_add(days) {
if ordinal > 0 && ordinal <= 365 {
let year_and_flags = self.ymdf & !ORDINAL_MASK;
return Some(NaiveDate { ymdf: year_and_flags | (ordinal << 4) });
}
}
// do the full check
let year = self.year();
let (mut year_div_400, year_mod_400) = div_mod_floor(year, 400);
let cycle = internals::yo_to_cycle(year_mod_400 as u32, self.of().ordinal());
let cycle = try_opt!((cycle as i32).checked_add(days));
let (cycle_div_400y, cycle) = div_mod_floor(cycle, 146_097);
year_div_400 += cycle_div_400y;
let (year_mod_400, ordinal) = internals::cycle_to_yo(cycle as u32);
let flags = YearFlags::from_year_mod_400(year_mod_400 as i32);
NaiveDate::from_ordinal_and_flags(year_div_400 * 400 + year_mod_400 as i32, ordinal, flags)
}
/// 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]
#[must_use]
pub const 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
///
/// Panics on invalid hour, minute and/or second.
#[deprecated(since = "0.4.23", note = "use `and_hms_opt()` instead")]
#[inline]
#[must_use]
pub const fn and_hms(&self, hour: u32, min: u32, sec: u32) -> NaiveDateTime {
expect!(self.and_hms_opt(hour, min, sec), "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.
///
/// # Errors
///
/// 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]
#[must_use]
pub const fn and_hms_opt(&self, hour: u32, min: u32, sec: u32) -> Option<NaiveDateTime> {
let time = try_opt!(NaiveTime::from_hms_opt(hour, min, sec));
Some(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
///
/// Panics on invalid hour, minute, second and/or millisecond.
#[deprecated(since = "0.4.23", note = "use `and_hms_milli_opt()` instead")]
#[inline]
#[must_use]
pub const fn and_hms_milli(&self, hour: u32, min: u32, sec: u32, milli: u32) -> NaiveDateTime {
expect!(self.and_hms_milli_opt(hour, min, sec, milli), "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).
///
/// # Errors
///
/// 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]
#[must_use]
pub const fn and_hms_milli_opt(
&self,
hour: u32,
min: u32,
sec: u32,
milli: u32,
) -> Option<NaiveDateTime> {
let time = try_opt!(NaiveTime::from_hms_milli_opt(hour, min, sec, milli));
Some(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
///
/// 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_opt(12, 34, 56, 789_012).unwrap();
/// 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]
#[must_use]
pub const fn and_hms_micro(&self, hour: u32, min: u32, sec: u32, micro: u32) -> NaiveDateTime {
expect!(self.and_hms_micro_opt(hour, min, sec, micro), "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).
///
/// # Errors
///
/// 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]
#[must_use]
pub const fn and_hms_micro_opt(
&self,
hour: u32,
min: u32,
sec: u32,
micro: u32,
) -> Option<NaiveDateTime> {
let time = try_opt!(NaiveTime::from_hms_micro_opt(hour, min, sec, micro));
Some(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
///
/// Panics on invalid hour, minute, second and/or nanosecond.
#[deprecated(since = "0.4.23", note = "use `and_hms_nano_opt()` instead")]
#[inline]
#[must_use]
pub const fn and_hms_nano(&self, hour: u32, min: u32, sec: u32, nano: u32) -> NaiveDateTime {
expect!(self.and_hms_nano_opt(hour, min, sec, nano), "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).