chrono/
traits.rs

1use crate::{IsoWeek, Weekday};
2
3/// The common set of methods for date component.
4///
5/// Methods such as [`year`], [`month`], [`day`] and [`weekday`] can be used to get basic
6/// information about the date.
7///
8/// The `with_*` methods can change the date.
9///
10/// # Warning
11///
12/// The `with_*` methods can be convenient to change a single component of a date, but they must be
13/// used with some care. Examples to watch out for:
14///
15/// - [`with_year`] changes the year component of a year-month-day value. Don't use this method if
16///   you want the ordinal to stay the same after changing the year, of if you want the week and
17///   weekday values to stay the same.
18/// - Don't combine two `with_*` methods to change two components of the date. For example to
19///   change both the year and month components of a date. This could fail because an intermediate
20///   value does not exist, while the final date would be valid.
21///
22/// For more complex changes to a date, it is best to use the methods on [`NaiveDate`] to create a
23/// new value instead of altering an existing date.
24///
25/// [`year`]: Datelike::year
26/// [`month`]: Datelike::month
27/// [`day`]: Datelike::day
28/// [`weekday`]: Datelike::weekday
29/// [`with_year`]: Datelike::with_year
30/// [`NaiveDate`]: crate::NaiveDate
31pub trait Datelike: Sized {
32    /// Returns the year number in the [calendar date](./naive/struct.NaiveDate.html#calendar-date).
33    fn year(&self) -> i32;
34
35    /// Returns the absolute year number starting from 1 with a boolean flag,
36    /// which is false when the year predates the epoch (BCE/BC) and true otherwise (CE/AD).
37    #[inline]
38    fn year_ce(&self) -> (bool, u32) {
39        let year = self.year();
40        if year < 1 {
41            (false, (1 - year) as u32)
42        } else {
43            (true, year as u32)
44        }
45    }
46
47    /// Returns the month number starting from 1.
48    ///
49    /// The return value ranges from 1 to 12.
50    fn month(&self) -> u32;
51
52    /// Returns the month number starting from 0.
53    ///
54    /// The return value ranges from 0 to 11.
55    fn month0(&self) -> u32;
56
57    /// Returns the day of month starting from 1.
58    ///
59    /// The return value ranges from 1 to 31. (The last day of month differs by months.)
60    fn day(&self) -> u32;
61
62    /// Returns the day of month starting from 0.
63    ///
64    /// The return value ranges from 0 to 30. (The last day of month differs by months.)
65    fn day0(&self) -> u32;
66
67    /// Returns the day of year starting from 1.
68    ///
69    /// The return value ranges from 1 to 366. (The last day of year differs by years.)
70    fn ordinal(&self) -> u32;
71
72    /// Returns the day of year starting from 0.
73    ///
74    /// The return value ranges from 0 to 365. (The last day of year differs by years.)
75    fn ordinal0(&self) -> u32;
76
77    /// Returns the day of week.
78    fn weekday(&self) -> Weekday;
79
80    /// Returns the ISO week.
81    fn iso_week(&self) -> IsoWeek;
82
83    /// Makes a new value with the year number changed, while keeping the same month and day.
84    ///
85    /// This method assumes you want to work on the date as a year-month-day value. Don't use it if
86    /// you want the ordinal to stay the same after changing the year, of if you want the week and
87    /// weekday values to stay the same.
88    ///
89    /// # Errors
90    ///
91    /// Returns `None` when:
92    ///
93    /// - The resulting date does not exist (February 29 in a non-leap year).
94    /// - The year is out of range for [`NaiveDate`].
95    /// - In case of [`DateTime<Tz>`] if the resulting date and time fall within a timezone
96    ///   transition such as from DST to standard time.
97    ///
98    /// [`NaiveDate`]: crate::NaiveDate
99    /// [`DateTime<Tz>`]: crate::DateTime
100    ///
101    /// # Examples
102    ///
103    /// ```
104    /// use chrono::{Datelike, NaiveDate};
105    ///
106    /// assert_eq!(
107    ///     NaiveDate::from_ymd_opt(2020, 5, 13).unwrap().with_year(2023).unwrap(),
108    ///     NaiveDate::from_ymd_opt(2023, 5, 13).unwrap()
109    /// );
110    /// // Resulting date 2023-02-29 does not exist:
111    /// assert!(NaiveDate::from_ymd_opt(2020, 2, 29).unwrap().with_year(2023).is_none());
112    ///
113    /// // Don't use `with_year` if you want the ordinal date to stay the same:
114    /// assert_ne!(
115    ///     NaiveDate::from_yo_opt(2020, 100).unwrap().with_year(2023).unwrap(),
116    ///     NaiveDate::from_yo_opt(2023, 100).unwrap() // result is 2023-101
117    /// );
118    /// ```
119    fn with_year(&self, year: i32) -> Option<Self>;
120
121    /// Makes a new value with the month number (starting from 1) changed.
122    ///
123    /// # Errors
124    ///
125    /// Returns `None` when:
126    ///
127    /// - The resulting date does not exist (for example `month(4)` when day of the month is 31).
128    /// - In case of [`DateTime<Tz>`] if the resulting date and time fall within a timezone
129    ///   transition such as from DST to standard time.
130    /// - The value for `month` is out of range.
131    ///
132    /// [`DateTime<Tz>`]: crate::DateTime
133    ///
134    /// # Examples
135    ///
136    /// ```
137    /// use chrono::{Datelike, NaiveDate};
138    ///
139    /// assert_eq!(
140    ///     NaiveDate::from_ymd_opt(2023, 5, 12).unwrap().with_month(9).unwrap(),
141    ///     NaiveDate::from_ymd_opt(2023, 9, 12).unwrap()
142    /// );
143    /// // Resulting date 2023-09-31 does not exist:
144    /// assert!(NaiveDate::from_ymd_opt(2023, 5, 31).unwrap().with_month(9).is_none());
145    /// ```
146    ///
147    /// Don't combine multiple `Datelike::with_*` methods. The intermediate value may not exist.
148    /// ```
149    /// use chrono::{Datelike, NaiveDate};
150    ///
151    /// fn with_year_month(date: NaiveDate, year: i32, month: u32) -> Option<NaiveDate> {
152    ///     date.with_year(year)?.with_month(month)
153    /// }
154    /// let d = NaiveDate::from_ymd_opt(2020, 2, 29).unwrap();
155    /// assert!(with_year_month(d, 2019, 1).is_none()); // fails because of invalid intermediate value
156    ///
157    /// // Correct version:
158    /// fn with_year_month_fixed(date: NaiveDate, year: i32, month: u32) -> Option<NaiveDate> {
159    ///     NaiveDate::from_ymd_opt(year, month, date.day())
160    /// }
161    /// let d = NaiveDate::from_ymd_opt(2020, 2, 29).unwrap();
162    /// assert_eq!(with_year_month_fixed(d, 2019, 1), NaiveDate::from_ymd_opt(2019, 1, 29));
163    /// ```
164    fn with_month(&self, month: u32) -> Option<Self>;
165
166    /// Makes a new value with the month number (starting from 0) changed.
167    ///
168    /// # Errors
169    ///
170    /// Returns `None` when:
171    ///
172    /// - The resulting date does not exist (for example `month0(3)` when day of the month is 31).
173    /// - In case of [`DateTime<Tz>`] if the resulting date and time fall within a timezone
174    ///   transition such as from DST to standard time.
175    /// - The value for `month0` is out of range.
176    ///
177    /// [`DateTime<Tz>`]: crate::DateTime
178    fn with_month0(&self, month0: u32) -> Option<Self>;
179
180    /// Makes a new value with the day of month (starting from 1) changed.
181    ///
182    /// # Errors
183    ///
184    /// Returns `None` when:
185    ///
186    /// - The resulting date does not exist (for example `day(31)` in April).
187    /// - In case of [`DateTime<Tz>`] if the resulting date and time fall within a timezone
188    ///   transition such as from DST to standard time.
189    /// - The value for `day` is out of range.
190    ///
191    /// [`DateTime<Tz>`]: crate::DateTime
192    fn with_day(&self, day: u32) -> Option<Self>;
193
194    /// Makes a new value with the day of month (starting from 0) changed.
195    ///
196    /// # Errors
197    ///
198    /// Returns `None` when:
199    ///
200    /// - The resulting date does not exist (for example `day0(30)` in April).
201    /// - In case of [`DateTime<Tz>`] if the resulting date and time fall within a timezone
202    ///   transition such as from DST to standard time.
203    /// - The value for `day0` is out of range.
204    ///
205    /// [`DateTime<Tz>`]: crate::DateTime
206    fn with_day0(&self, day0: u32) -> Option<Self>;
207
208    /// Makes a new value with the day of year (starting from 1) changed.
209    ///
210    /// # Errors
211    ///
212    /// Returns `None` when:
213    ///
214    /// - The resulting date does not exist (`with_ordinal(366)` in a non-leap year).
215    /// - In case of [`DateTime<Tz>`] if the resulting date and time fall within a timezone
216    ///   transition such as from DST to standard time.
217    /// - The value for `ordinal` is out of range.
218    ///
219    /// [`DateTime<Tz>`]: crate::DateTime
220    fn with_ordinal(&self, ordinal: u32) -> Option<Self>;
221
222    /// Makes a new value with the day of year (starting from 0) changed.
223    ///
224    /// # Errors
225    ///
226    /// Returns `None` when:
227    ///
228    /// - The resulting date does not exist (`with_ordinal0(365)` in a non-leap year).
229    /// - In case of [`DateTime<Tz>`] if the resulting date and time fall within a timezone
230    ///   transition such as from DST to standard time.
231    /// - The value for `ordinal0` is out of range.
232    ///
233    /// [`DateTime<Tz>`]: crate::DateTime
234    fn with_ordinal0(&self, ordinal0: u32) -> Option<Self>;
235
236    /// Counts the days in the proleptic Gregorian calendar, with January 1, Year 1 (CE) as day 1.
237    ///
238    /// # Examples
239    ///
240    /// ```
241    /// use chrono::{Datelike, NaiveDate};
242    ///
243    /// assert_eq!(NaiveDate::from_ymd_opt(1970, 1, 1).unwrap().num_days_from_ce(), 719_163);
244    /// assert_eq!(NaiveDate::from_ymd_opt(2, 1, 1).unwrap().num_days_from_ce(), 366);
245    /// assert_eq!(NaiveDate::from_ymd_opt(1, 1, 1).unwrap().num_days_from_ce(), 1);
246    /// assert_eq!(NaiveDate::from_ymd_opt(0, 1, 1).unwrap().num_days_from_ce(), -365);
247    /// ```
248    fn num_days_from_ce(&self) -> i32 {
249        // See test_num_days_from_ce_against_alternative_impl below for a more straightforward
250        // implementation.
251
252        // we know this wouldn't overflow since year is limited to 1/2^13 of i32's full range.
253        let mut year = self.year() - 1;
254        let mut ndays = 0;
255        if year < 0 {
256            let excess = 1 + (-year) / 400;
257            year += excess * 400;
258            ndays -= excess * 146_097;
259        }
260        let div_100 = year / 100;
261        ndays += ((year * 1461) >> 2) - div_100 + (div_100 >> 2);
262        ndays + self.ordinal() as i32
263    }
264}
265
266/// The common set of methods for time component.
267pub trait Timelike: Sized {
268    /// Returns the hour number from 0 to 23.
269    fn hour(&self) -> u32;
270
271    /// Returns the hour number from 1 to 12 with a boolean flag,
272    /// which is false for AM and true for PM.
273    #[inline]
274    fn hour12(&self) -> (bool, u32) {
275        let hour = self.hour();
276        let mut hour12 = hour % 12;
277        if hour12 == 0 {
278            hour12 = 12;
279        }
280        (hour >= 12, hour12)
281    }
282
283    /// Returns the minute number from 0 to 59.
284    fn minute(&self) -> u32;
285
286    /// Returns the second number from 0 to 59.
287    fn second(&self) -> u32;
288
289    /// Returns the number of nanoseconds since the whole non-leap second.
290    /// The range from 1,000,000,000 to 1,999,999,999 represents
291    /// the [leap second](./naive/struct.NaiveTime.html#leap-second-handling).
292    fn nanosecond(&self) -> u32;
293
294    /// Makes a new value with the hour number changed.
295    ///
296    /// Returns `None` when the resulting value would be invalid.
297    fn with_hour(&self, hour: u32) -> Option<Self>;
298
299    /// Makes a new value with the minute number changed.
300    ///
301    /// Returns `None` when the resulting value would be invalid.
302    fn with_minute(&self, min: u32) -> Option<Self>;
303
304    /// Makes a new value with the second number changed.
305    ///
306    /// Returns `None` when the resulting value would be invalid.
307    /// As with the [`second`](#tymethod.second) method,
308    /// the input range is restricted to 0 through 59.
309    fn with_second(&self, sec: u32) -> Option<Self>;
310
311    /// Makes a new value with nanoseconds since the whole non-leap second changed.
312    ///
313    /// Returns `None` when the resulting value would be invalid.
314    /// As with the [`nanosecond`](#tymethod.nanosecond) method,
315    /// the input range can exceed 1,000,000,000 for leap seconds.
316    fn with_nanosecond(&self, nano: u32) -> Option<Self>;
317
318    /// Returns the number of non-leap seconds past the last midnight.
319    ///
320    /// Every value in 00:00:00-23:59:59 maps to an integer in 0-86399.
321    ///
322    /// This method is not intended to provide the real number of seconds since midnight on a given
323    /// day. It does not take things like DST transitions into account.
324    #[inline]
325    fn num_seconds_from_midnight(&self) -> u32 {
326        self.hour() * 3600 + self.minute() * 60 + self.second()
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::Datelike;
333    use crate::{Days, NaiveDate};
334
335    /// Tests `Datelike::num_days_from_ce` against an alternative implementation.
336    ///
337    /// The alternative implementation is not as short as the current one but it is simpler to
338    /// understand, with less unexplained magic constants.
339    #[test]
340    fn test_num_days_from_ce_against_alternative_impl() {
341        /// Returns the number of multiples of `div` in the range `start..end`.
342        ///
343        /// If the range `start..end` is back-to-front, i.e. `start` is greater than `end`, the
344        /// behaviour is defined by the following equation:
345        /// `in_between(start, end, div) == - in_between(end, start, div)`.
346        ///
347        /// When `div` is 1, this is equivalent to `end - start`, i.e. the length of `start..end`.
348        ///
349        /// # Panics
350        ///
351        /// Panics if `div` is not positive.
352        fn in_between(start: i32, end: i32, div: i32) -> i32 {
353            assert!(div > 0, "in_between: nonpositive div = {}", div);
354            let start = (start.div_euclid(div), start.rem_euclid(div));
355            let end = (end.div_euclid(div), end.rem_euclid(div));
356            // The lowest multiple of `div` greater than or equal to `start`, divided.
357            let start = start.0 + (start.1 != 0) as i32;
358            // The lowest multiple of `div` greater than or equal to   `end`, divided.
359            let end = end.0 + (end.1 != 0) as i32;
360            end - start
361        }
362
363        /// Alternative implementation to `Datelike::num_days_from_ce`
364        fn num_days_from_ce<Date: Datelike>(date: &Date) -> i32 {
365            let year = date.year();
366            let diff = move |div| in_between(1, year, div);
367            // 365 days a year, one more in leap years. In the gregorian calendar, leap years are all
368            // the multiples of 4 except multiples of 100 but including multiples of 400.
369            date.ordinal() as i32 + 365 * diff(1) + diff(4) - diff(100) + diff(400)
370        }
371
372        for year in NaiveDate::MIN.year()..=NaiveDate::MAX.year() {
373            let jan1_year = NaiveDate::from_ymd_opt(year, 1, 1).unwrap();
374            assert_eq!(
375                jan1_year.num_days_from_ce(),
376                num_days_from_ce(&jan1_year),
377                "on {:?}",
378                jan1_year
379            );
380            let mid_year = jan1_year + Days::new(133);
381            assert_eq!(
382                mid_year.num_days_from_ce(),
383                num_days_from_ce(&mid_year),
384                "on {:?}",
385                mid_year
386            );
387        }
388    }
389}