Skip to main content

time_zone/
civil.rs

1//! Proleptic Gregorian calendar arithmetic without allocation.
2//!
3//! Days are counted from 1970-01-01, the Unix epoch. The formulas are the
4//! civil-from-days and days-from-civil algorithms published by Howard Hinnant
5//! (<https://howardhinnant.github.io/date_algorithms.html>); the variable names
6//! `mp`, `doe`, `yoe` and `doy` below are the ones of that published algorithm.
7
8/// Seconds in one day.
9pub(crate) const SECONDS_PER_DAY: i64 = 86_400;
10
11/// A broken down date and time in the proleptic Gregorian calendar.
12///
13/// The fields must hold the values of their names (month 1 to 12, and so on);
14/// see [`DateTime::is_valid`]. Conversions do not check them.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct DateTime {
17    /// The year, for example 2026.
18    pub year: i64,
19    /// The month of the year, 1 to 12.
20    pub month: u8,
21    /// The day of the month, 1 to 31.
22    pub day: u8,
23    /// The hour of the day, 0 to 23.
24    pub hour: u8,
25    /// The minute of the hour, 0 to 59.
26    pub minute: u8,
27    /// The second of the minute, 0 to 59. Leap seconds are not represented.
28    pub second: u8,
29}
30
31impl DateTime {
32    /// Whether every field holds a value of its name: month 1 to 12, day 1 to
33    /// the length of the month, hour 0 to 23, minute and second 0 to 59.
34    pub const fn is_valid(&self) -> bool {
35        self.month >= 1
36            && self.month <= 12
37            && self.day >= 1
38            && self.day <= days_in_month(self.year, self.month)
39            && self.hour <= 23
40            && self.minute <= 59
41            && self.second <= 59
42    }
43
44    /// Seconds since the Unix epoch of this date and time read as UTC, or
45    /// `None` when the fields are so far out that the count leaves the `i64`
46    /// range. The fields themselves are not checked; see [`DateTime::is_valid`].
47    pub(crate) fn unix_seconds_checked(self) -> Option<i64> {
48        let days = days_from_civil_checked(self.year, self.month, self.day)?;
49        let second_of_day =
50            i64::from(self.hour) * 3600 + i64::from(self.minute) * 60 + i64::from(self.second);
51        days.checked_mul(SECONDS_PER_DAY)?
52            .checked_add(second_of_day)
53    }
54}
55
56/// Days from 1970-01-01 to the given civil date, or `None` when the year is
57/// so far out that the count leaves the `i64` range. Used only for unchecked
58/// local input of [`crate::TimeZone::to_utc`]; the hot paths use
59/// [`days_from_civil`] and [`civil_from_days`], whose results always stay in
60/// range.
61pub(crate) fn days_from_civil_checked(year: i64, month: u8, day: u8) -> Option<i64> {
62    let year = if month <= 2 {
63        year.checked_sub(1)?
64    } else {
65        year
66    };
67    let era = year.div_euclid(400);
68    let yoe = year.rem_euclid(400); // [0, 399]
69    let mp = (month as i64 + 9) % 12; // March is 0
70    let doy = (153 * mp + 2) / 5 + day as i64 - 1; // [0, 365]
71    let doe = yoe
72        .checked_mul(365)?
73        .checked_add(yoe / 4)?
74        .checked_sub(yoe / 100)?
75        .checked_add(doy)?; // [0, 146096]
76    era.checked_mul(146_097)?
77        .checked_add(doe)?
78        .checked_sub(719_468)
79}
80
81/// Days from 1970-01-01 to the given civil date. The inverse of
82/// [`civil_from_days`]. Every `i64` second count maps to a day count that
83/// stays inside the `i64` range, so `i64` arithmetic is exact here and keeps
84/// the code small on targets without a hardware divide.
85pub const fn days_from_civil(year: i64, month: u8, day: u8) -> i64 {
86    let year = if month <= 2 { year - 1 } else { year };
87    let era = year.div_euclid(400);
88    let yoe = year - era * 400; // [0, 399]
89    let mp = (month as i64 + 9) % 12; // March is 0
90    let doy = (153 * mp + 2) / 5 + day as i64 - 1; // [0, 365]
91    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
92    era * 146_097 + doe - 719_468
93}
94
95/// The civil date of a day count from 1970-01-01, as (year, month, day).
96/// The inverse of [`days_from_civil`].
97pub const fn civil_from_days(days: i64) -> (i64, u8, u8) {
98    let days = days + 719_468;
99    let era = days.div_euclid(146_097);
100    let doe = days - era * 146_097; // [0, 146096]
101    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
102    let year = yoe + era * 400;
103    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
104    let mp = (5 * doy + 2) / 153; // [0, 11]
105    let day = (doy - (153 * mp + 2) / 5 + 1) as u8; // [1, 31]
106    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u8; // [1, 12]
107    (if month <= 2 { year + 1 } else { year }, month, day)
108}
109
110/// The day of the week of a day count from 1970-01-01, 0 for Sunday.
111pub(crate) const fn weekday_from_days(days: i64) -> u8 {
112    ((days + 4).rem_euclid(7)) as u8
113}
114
115/// Whether a year is a leap year in the Gregorian calendar.
116pub(crate) const fn is_leap_year(year: i64) -> bool {
117    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
118}
119
120/// The number of days in a month, or 0 for a month outside 1 to 12.
121pub(crate) const fn days_in_month(year: i64, month: u8) -> u8 {
122    match month {
123        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
124        4 | 6 | 9 | 11 => 30,
125        2 if is_leap_year(year) => 29,
126        2 => 28,
127        _ => 0,
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn epoch_is_1970_01_01() {
137        assert_eq!(days_from_civil(1970, 1, 1), 0);
138        assert_eq!(civil_from_days(0), (1970, 1, 1));
139        assert_eq!(weekday_from_days(0), 4); // Thursday
140    }
141
142    #[test]
143    fn round_trip_over_a_wide_range() {
144        let mut days = -800_000;
145        while days < 800_000 {
146            let (year, month, day) = civil_from_days(days);
147            assert_eq!(days_from_civil(year, month, day), days);
148            days += 977;
149        }
150    }
151
152    #[test]
153    fn leap_rules() {
154        assert!(is_leap_year(2000));
155        assert!(!is_leap_year(1900));
156        assert!(is_leap_year(2024));
157        assert_eq!(days_in_month(2024, 2), 29);
158        assert_eq!(days_in_month(2023, 2), 28);
159        assert_eq!(
160            civil_from_days(days_from_civil(2024, 3, 1) - 1),
161            (2024, 2, 29)
162        );
163    }
164
165    #[test]
166    fn date_time_validity() {
167        assert!(
168            DateTime {
169                year: 2024,
170                month: 2,
171                day: 29,
172                hour: 23,
173                minute: 59,
174                second: 59
175            }
176            .is_valid()
177        );
178        assert!(
179            !DateTime {
180                year: 2023,
181                month: 2,
182                day: 29,
183                hour: 0,
184                minute: 0,
185                second: 0
186            }
187            .is_valid()
188        );
189        assert!(
190            !DateTime {
191                year: 2024,
192                month: 13,
193                day: 1,
194                hour: 0,
195                minute: 0,
196                second: 0
197            }
198            .is_valid()
199        );
200        assert!(
201            !DateTime {
202                year: 2024,
203                month: 0,
204                day: 1,
205                hour: 0,
206                minute: 0,
207                second: 0
208            }
209            .is_valid()
210        );
211        assert!(
212            !DateTime {
213                year: 2024,
214                month: 4,
215                day: 31,
216                hour: 0,
217                minute: 0,
218                second: 0
219            }
220            .is_valid()
221        );
222        assert!(
223            !DateTime {
224                year: 2024,
225                month: 1,
226                day: 1,
227                hour: 24,
228                minute: 0,
229                second: 0
230            }
231            .is_valid()
232        );
233        assert!(
234            !DateTime {
235                year: 2024,
236                month: 1,
237                day: 1,
238                hour: 0,
239                minute: 60,
240                second: 0
241            }
242            .is_valid()
243        );
244        assert!(
245            !DateTime {
246                year: 2024,
247                month: 1,
248                day: 1,
249                hour: 0,
250                minute: 0,
251                second: 60
252            }
253            .is_valid()
254        );
255        assert!(
256            !DateTime {
257                year: 2024,
258                month: 1,
259                day: 0,
260                hour: 0,
261                minute: 0,
262                second: 0
263            }
264            .is_valid()
265        );
266    }
267}