1use crate::{IsoWeek, Weekday};
2
3/// The common set of methods for date component.
4pub trait Datelike: Sized {
5 /// Returns the year number in the [calendar date](./naive/struct.NaiveDate.html#calendar-date).
6 fn year(&self) -> i32;
7
8 /// Returns the absolute year number starting from 1 with a boolean flag,
9 /// which is false when the year predates the epoch (BCE/BC) and true otherwise (CE/AD).
10 #[inline]
11 fn year_ce(&self) -> (bool, u32) {
12 let year = self.year();
13 if year < 1 {
14 (false, (1 - year) as u32)
15 } else {
16 (true, year as u32)
17 }
18 }
19
20 /// Returns the month number starting from 1.
21 ///
22 /// The return value ranges from 1 to 12.
23 fn month(&self) -> u32;
24
25 /// Returns the month number starting from 0.
26 ///
27 /// The return value ranges from 0 to 11.
28 fn month0(&self) -> u32;
29
30 /// Returns the day of month starting from 1.
31 ///
32 /// The return value ranges from 1 to 31. (The last day of month differs by months.)
33 fn day(&self) -> u32;
34
35 /// Returns the day of month starting from 0.
36 ///
37 /// The return value ranges from 0 to 30. (The last day of month differs by months.)
38 fn day0(&self) -> u32;
39
40 /// Returns the day of year starting from 1.
41 ///
42 /// The return value ranges from 1 to 366. (The last day of year differs by years.)
43 fn ordinal(&self) -> u32;
44
45 /// Returns the day of year starting from 0.
46 ///
47 /// The return value ranges from 0 to 365. (The last day of year differs by years.)
48 fn ordinal0(&self) -> u32;
49
50 /// Returns the day of week.
51 fn weekday(&self) -> Weekday;
52
53 /// Returns the ISO week.
54 fn iso_week(&self) -> IsoWeek;
55
56 /// Makes a new value with the year number changed.
57 ///
58 /// Returns `None` when the resulting value would be invalid.
59 fn with_year(&self, year: i32) -> Option<Self>;
60
61 /// Makes a new value with the month number (starting from 1) changed.
62 ///
63 /// Returns `None` when the resulting value would be invalid.
64 fn with_month(&self, month: u32) -> Option<Self>;
65
66 /// Makes a new value with the month number (starting from 0) changed.
67 ///
68 /// Returns `None` when the resulting value would be invalid.
69 fn with_month0(&self, month0: u32) -> Option<Self>;
70
71 /// Makes a new value with the day of month (starting from 1) changed.
72 ///
73 /// Returns `None` when the resulting value would be invalid.
74 fn with_day(&self, day: u32) -> Option<Self>;
75
76 /// Makes a new value with the day of month (starting from 0) changed.
77 ///
78 /// Returns `None` when the resulting value would be invalid.
79 fn with_day0(&self, day0: u32) -> Option<Self>;
80
81 /// Makes a new value with the day of year (starting from 1) changed.
82 ///
83 /// Returns `None` when the resulting value would be invalid.
84 fn with_ordinal(&self, ordinal: u32) -> Option<Self>;
85
86 /// Makes a new value with the day of year (starting from 0) changed.
87 ///
88 /// Returns `None` when the resulting value would be invalid.
89 fn with_ordinal0(&self, ordinal0: u32) -> Option<Self>;
90
91 /// Counts the days in the proleptic Gregorian calendar, with January 1, Year 1 (CE) as day 1.
92 ///
93 /// # Examples
94 ///
95 /// ```
96 /// use chrono::{NaiveDate, Datelike};
97 ///
98 /// assert_eq!(NaiveDate::from_ymd_opt(1970, 1, 1).unwrap().num_days_from_ce(), 719_163);
99 /// assert_eq!(NaiveDate::from_ymd_opt(2, 1, 1).unwrap().num_days_from_ce(), 366);
100 /// assert_eq!(NaiveDate::from_ymd_opt(1, 1, 1).unwrap().num_days_from_ce(), 1);
101 /// assert_eq!(NaiveDate::from_ymd_opt(0, 1, 1).unwrap().num_days_from_ce(), -365);
102 /// ```
103 fn num_days_from_ce(&self) -> i32 {
104 // See test_num_days_from_ce_against_alternative_impl below for a more straightforward
105 // implementation.
106
107 // we know this wouldn't overflow since year is limited to 1/2^13 of i32's full range.
108 let mut year = self.year() - 1;
109 let mut ndays = 0;
110 if year < 0 {
111 let excess = 1 + (-year) / 400;
112 year += excess * 400;
113 ndays -= excess * 146_097;
114 }
115 let div_100 = year / 100;
116 ndays += ((year * 1461) >> 2) - div_100 + (div_100 >> 2);
117 ndays + self.ordinal() as i32
118 }
119}
120
121/// The common set of methods for time component.
122pub trait Timelike: Sized {
123 /// Returns the hour number from 0 to 23.
124 fn hour(&self) -> u32;
125
126 /// Returns the hour number from 1 to 12 with a boolean flag,
127 /// which is false for AM and true for PM.
128 #[inline]
129 fn hour12(&self) -> (bool, u32) {
130 let hour = self.hour();
131 let mut hour12 = hour % 12;
132 if hour12 == 0 {
133 hour12 = 12;
134 }
135 (hour >= 12, hour12)
136 }
137
138 /// Returns the minute number from 0 to 59.
139 fn minute(&self) -> u32;
140
141 /// Returns the second number from 0 to 59.
142 fn second(&self) -> u32;
143
144 /// Returns the number of nanoseconds since the whole non-leap second.
145 /// The range from 1,000,000,000 to 1,999,999,999 represents
146 /// the [leap second](./naive/struct.NaiveTime.html#leap-second-handling).
147 fn nanosecond(&self) -> u32;
148
149 /// Makes a new value with the hour number changed.
150 ///
151 /// Returns `None` when the resulting value would be invalid.
152 fn with_hour(&self, hour: u32) -> Option<Self>;
153
154 /// Makes a new value with the minute number changed.
155 ///
156 /// Returns `None` when the resulting value would be invalid.
157 fn with_minute(&self, min: u32) -> Option<Self>;
158
159 /// Makes a new value with the second number changed.
160 ///
161 /// Returns `None` when the resulting value would be invalid.
162 /// As with the [`second`](#tymethod.second) method,
163 /// the input range is restricted to 0 through 59.
164 fn with_second(&self, sec: u32) -> Option<Self>;
165
166 /// Makes a new value with nanoseconds since the whole non-leap second changed.
167 ///
168 /// Returns `None` when the resulting value would be invalid.
169 /// As with the [`nanosecond`](#tymethod.nanosecond) method,
170 /// the input range can exceed 1,000,000,000 for leap seconds.
171 fn with_nanosecond(&self, nano: u32) -> Option<Self>;
172
173 /// Returns the number of non-leap seconds past the last midnight.
174 #[inline]
175 fn num_seconds_from_midnight(&self) -> u32 {
176 self.hour() * 3600 + self.minute() * 60 + self.second()
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use super::Datelike;
183 use crate::{Duration, NaiveDate};
184
185 /// Tests `Datelike::num_days_from_ce` against an alternative implementation.
186 ///
187 /// The alternative implementation is not as short as the current one but it is simpler to
188 /// understand, with less unexplained magic constants.
189 #[test]
190 fn test_num_days_from_ce_against_alternative_impl() {
191 /// Returns the number of multiples of `div` in the range `start..end`.
192 ///
193 /// If the range `start..end` is back-to-front, i.e. `start` is greater than `end`, the
194 /// behaviour is defined by the following equation:
195 /// `in_between(start, end, div) == - in_between(end, start, div)`.
196 ///
197 /// When `div` is 1, this is equivalent to `end - start`, i.e. the length of `start..end`.
198 ///
199 /// # Panics
200 ///
201 /// Panics if `div` is not positive.
202 fn in_between(start: i32, end: i32, div: i32) -> i32 {
203 assert!(div > 0, "in_between: nonpositive div = {}", div);
204 let start = (start.div_euclid(div), start.rem_euclid(div));
205 let end = (end.div_euclid(div), end.rem_euclid(div));
206 // The lowest multiple of `div` greater than or equal to `start`, divided.
207 let start = start.0 + (start.1 != 0) as i32;
208 // The lowest multiple of `div` greater than or equal to `end`, divided.
209 let end = end.0 + (end.1 != 0) as i32;
210 end - start
211 }
212
213 /// Alternative implementation to `Datelike::num_days_from_ce`
214 fn num_days_from_ce<Date: Datelike>(date: &Date) -> i32 {
215 let year = date.year();
216 let diff = move |div| in_between(1, year, div);
217 // 365 days a year, one more in leap years. In the gregorian calendar, leap years are all
218 // the multiples of 4 except multiples of 100 but including multiples of 400.
219 date.ordinal() as i32 + 365 * diff(1) + diff(4) - diff(100) + diff(400)
220 }
221
222 for year in NaiveDate::MIN.year()..=NaiveDate::MAX.year() {
223 let jan1_year = NaiveDate::from_ymd_opt(year, 1, 1).unwrap();
224 assert_eq!(
225 jan1_year.num_days_from_ce(),
226 num_days_from_ce(&jan1_year),
227 "on {:?}",
228 jan1_year
229 );
230 let mid_year = jan1_year + Duration::days(133);
231 assert_eq!(
232 mid_year.num_days_from_ce(),
233 num_days_from_ce(&mid_year),
234 "on {:?}",
235 mid_year
236 );
237 }
238 }
239}
240