chrono/naive/
mod.rs

1//! Date and time types unconcerned with timezones.
2//!
3//! They are primarily building blocks for other types
4//! (e.g. [`TimeZone`](../offset/trait.TimeZone.html)),
5//! but can be also used for the simpler date and time handling.
6
7use core::ops::RangeInclusive;
8
9use crate::expect;
10use crate::Weekday;
11
12pub(crate) mod date;
13pub(crate) mod datetime;
14mod internals;
15pub(crate) mod isoweek;
16pub(crate) mod time;
17
18pub use self::date::{NaiveDate, NaiveDateDaysIterator, NaiveDateWeeksIterator};
19#[allow(deprecated)]
20pub use self::date::{MAX_DATE, MIN_DATE};
21#[allow(deprecated)]
22pub use self::datetime::{NaiveDateTime, MAX_DATETIME, MIN_DATETIME};
23pub use self::isoweek::IsoWeek;
24pub use self::time::NaiveTime;
25
26#[cfg(feature = "__internal_bench")]
27#[doc(hidden)]
28pub use self::internals::YearFlags as __BenchYearFlags;
29
30/// A week represented by a [`NaiveDate`] and a [`Weekday`] which is the first
31/// day of the week.
32#[derive(Debug)]
33pub struct NaiveWeek {
34    date: NaiveDate,
35    start: Weekday,
36}
37
38impl NaiveWeek {
39    /// Create a new `NaiveWeek`
40    pub(crate) const fn new(date: NaiveDate, start: Weekday) -> Self {
41        Self { date, start }
42    }
43
44    /// Returns a date representing the first day of the week.
45    ///
46    /// # Panics
47    ///
48    /// Panics if the first day of the week happens to fall just out of range of `NaiveDate`
49    /// (more than ca. 262,000 years away from common era).
50    ///
51    /// # Examples
52    ///
53    /// ```
54    /// use chrono::{NaiveDate, Weekday};
55    ///
56    /// let date = NaiveDate::from_ymd_opt(2022, 4, 18).unwrap();
57    /// let week = date.week(Weekday::Mon);
58    /// assert!(week.first_day() <= date);
59    /// ```
60    #[inline]
61    #[must_use]
62    pub const fn first_day(&self) -> NaiveDate {
63        let start = self.start.num_days_from_monday() as i32;
64        let ref_day = self.date.weekday().num_days_from_monday() as i32;
65        // Calculate the number of days to subtract from `self.date`.
66        // Do not construct an intermediate date beyond `self.date`, because that may be out of
67        // range if `date` is close to `NaiveDate::MAX`.
68        let days = start - ref_day - if start > ref_day { 7 } else { 0 };
69        expect(self.date.add_days(days), "first weekday out of range for `NaiveDate`")
70    }
71
72    /// Returns a date representing the last day of the week.
73    ///
74    /// # Panics
75    ///
76    /// Panics if the last day of the week happens to fall just out of range of `NaiveDate`
77    /// (more than ca. 262,000 years away from common era).
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// use chrono::{NaiveDate, Weekday};
83    ///
84    /// let date = NaiveDate::from_ymd_opt(2022, 4, 18).unwrap();
85    /// let week = date.week(Weekday::Mon);
86    /// assert!(week.last_day() >= date);
87    /// ```
88    #[inline]
89    #[must_use]
90    pub const fn last_day(&self) -> NaiveDate {
91        let end = self.start.pred().num_days_from_monday() as i32;
92        let ref_day = self.date.weekday().num_days_from_monday() as i32;
93        // Calculate the number of days to add to `self.date`.
94        // Do not construct an intermediate date before `self.date` (like with `first_day()`),
95        // because that may be out of range if `date` is close to `NaiveDate::MIN`.
96        let days = end - ref_day + if end < ref_day { 7 } else { 0 };
97        expect(self.date.add_days(days), "last weekday out of range for `NaiveDate`")
98    }
99
100    /// Returns a [`RangeInclusive<T>`] representing the whole week bounded by
101    /// [first_day](NaiveWeek::first_day) and [last_day](NaiveWeek::last_day) functions.
102    ///
103    /// # Panics
104    ///
105    /// Panics if the either the first or last day of the week happens to fall just out of range of
106    /// `NaiveDate` (more than ca. 262,000 years away from common era).
107    ///
108    /// # Examples
109    ///
110    /// ```
111    /// use chrono::{NaiveDate, Weekday};
112    ///
113    /// let date = NaiveDate::from_ymd_opt(2022, 4, 18).unwrap();
114    /// let week = date.week(Weekday::Mon);
115    /// let days = week.days();
116    /// assert!(days.contains(&date));
117    /// ```
118    #[inline]
119    #[must_use]
120    pub const fn days(&self) -> RangeInclusive<NaiveDate> {
121        self.first_day()..=self.last_day()
122    }
123}
124
125/// A duration in calendar days.
126///
127/// This is useful because when using `TimeDelta` it is possible that adding `TimeDelta::days(1)`
128/// doesn't increment the day value as expected due to it being a fixed number of seconds. This
129/// difference applies only when dealing with `DateTime<TimeZone>` data types and in other cases
130/// `TimeDelta::days(n)` and `Days::new(n)` are equivalent.
131#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
132pub struct Days(pub(crate) u64);
133
134impl Days {
135    /// Construct a new `Days` from a number of days
136    pub const fn new(num: u64) -> Self {
137        Self(num)
138    }
139}
140
141/// Serialization/Deserialization of `NaiveDateTime` in alternate formats
142///
143/// The various modules in here are intended to be used with serde's [`with` annotation] to
144/// serialize as something other than the default ISO 8601 format.
145///
146/// [`with` annotation]: https://serde.rs/field-attrs.html#with
147#[cfg(feature = "serde")]
148pub mod serde {
149    pub use super::datetime::serde::*;
150}
151
152#[cfg(test)]
153mod test {
154    use crate::{NaiveDate, Weekday};
155    #[test]
156    fn test_naiveweek() {
157        let date = NaiveDate::from_ymd_opt(2022, 5, 18).unwrap();
158        let asserts = [
159            (Weekday::Mon, "Mon 2022-05-16", "Sun 2022-05-22"),
160            (Weekday::Tue, "Tue 2022-05-17", "Mon 2022-05-23"),
161            (Weekday::Wed, "Wed 2022-05-18", "Tue 2022-05-24"),
162            (Weekday::Thu, "Thu 2022-05-12", "Wed 2022-05-18"),
163            (Weekday::Fri, "Fri 2022-05-13", "Thu 2022-05-19"),
164            (Weekday::Sat, "Sat 2022-05-14", "Fri 2022-05-20"),
165            (Weekday::Sun, "Sun 2022-05-15", "Sat 2022-05-21"),
166        ];
167        for (start, first_day, last_day) in asserts {
168            let week = date.week(start);
169            let days = week.days();
170            assert_eq!(Ok(week.first_day()), NaiveDate::parse_from_str(first_day, "%a %Y-%m-%d"));
171            assert_eq!(Ok(week.last_day()), NaiveDate::parse_from_str(last_day, "%a %Y-%m-%d"));
172            assert!(days.contains(&date));
173        }
174    }
175
176    #[test]
177    fn test_naiveweek_min_max() {
178        let date_max = NaiveDate::MAX;
179        assert!(date_max.week(Weekday::Mon).first_day() <= date_max);
180        let date_min = NaiveDate::MIN;
181        assert!(date_min.week(Weekday::Mon).last_day() >= date_min);
182    }
183}