Skip to main content

deep_time/dt/
gregorian.rs

1use crate::{ATTOS_PER_SEC, Dt, SEC_PER_DAYI64, Scale, Weekday, YmdHms, leap_seconds::leap_sec};
2
3impl Dt {
4    pub(crate) const DAYS_IN_GREGORIAN_MONTHS: [u8; 12] =
5        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
6
7    // pub(crate) const DAYS_IN_GREGORIAN_MONTHS_LEAP_YR: [u8; 12] =
8    //     [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
9
10    /// Converts a Unix timestamp (seconds since 1970-01-01 00:00:00)
11    /// to a proleptic Gregorian date (year, month, day).
12    pub const fn unix_sec_to_ymd(unix_sec: i64) -> (i64, u8, u8) {
13        let days = unix_sec.div_euclid(86400);
14
15        // Shift so we work relative to 0000-03-01 (makes leap year math cleaner)
16        let z = days + 719468;
17
18        let era = if z >= 0 {
19            z / 146097
20        } else {
21            (z - 146096) / 146097
22        };
23        let doe = z - era * 146097; // [0, 146096]
24        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399]
25        let y = yoe + era * 400;
26        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
27        let mp = (5 * doy + 2) / 153; // [0, 11]
28        let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
29        let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
30
31        let yr = y + if m <= 2 { 1 } else { 0 };
32
33        (yr, m as u8, d as u8)
34    }
35
36    /// Returns the calendar date and time for this instant.
37    ///
38    /// Converts to this [`Dt`]s `target` time scale using the internal current
39    /// `scale` before producing a result.
40    ///
41    /// ## Returns
42    ///
43    /// A [`YmdHms`] containing:
44    ///
45    /// - `yr`, `mo`, `day` — calendar date
46    /// - `hr` (0–23), `min` (0–59), `sec` (0–60)
47    /// - `attos` — fractional second in attoseconds (`0 ≤ attos < 10¹⁸`)
48    /// - `scale` — time scale that the object is in
49    ///
50    /// ## Leap-second handling
51    ///
52    /// If the [`Dt`]'s `target` time scale is one of the scales that use leap seconds
53    /// (`UTC`, `UtcSpice`, or `UtcHist`) **and** the instant falls exactly on a leap
54    /// second, (requires the objects current time scale **not** be UTC) the returned
55    /// `sec` will be `60`. In every other case `sec` is in the range `0..=59`.
56    ///
57    /// The implementation converts internally to TAI before checking leap-second status.
58    ///
59    /// ## Examples
60    ///
61    /// ```rust
62    /// use deep_time::{Dt, Scale};
63    ///
64    /// // `from_ymd` always returns a TAI instant
65    /// let dt = Dt::from_ymd(2024, 6, 15, Scale::UTC, 12, 30, 45, 0);
66    /// let ymd = dt.to_ymd();
67    ///
68    /// assert_eq!(ymd.yr(), 2024);
69    /// assert_eq!(ymd.mo(), 6);
70    /// assert_eq!(ymd.day(), 15);
71    /// assert_eq!(ymd.hr(), 12);
72    /// assert_eq!(ymd.min(), 30);
73    /// assert_eq!(ymd.sec(), 45);
74    /// assert!(ymd.attos() == 0);
75    /// ```
76    ///
77    /// ## See also
78    ///
79    /// - [`Dt::from_ymd`](../struct.Dt.html#method.from_ymd)
80    pub const fn to_ymd(&self) -> YmdHms {
81        let from_unix_epoch = self.to_scale_and_diff(Dt::UNIX_EPOCH, true);
82
83        let unix_sec = from_unix_epoch.to_sec64();
84        let frac = from_unix_epoch.to_sec_ufrac();
85        let (yr, mo, day) = Self::unix_sec_to_ymd(unix_sec);
86
87        let seconds_since_midnight = unix_sec.rem_euclid(SEC_PER_DAYI64);
88        let hr = (seconds_since_midnight / 3600) as u8;
89        let min = ((seconds_since_midnight % 3600) / 60) as u8;
90        let mut sec = (seconds_since_midnight % 60) as u8;
91        let is_leap = if self.target.uses_leap_seconds() {
92            match self.to_tai().leap_sec(false) {
93                Some(i) => i.is_leap_sec,
94                None => false,
95            }
96        } else {
97            false
98        };
99        if is_leap {
100            sec += 1;
101        }
102
103        YmdHms {
104            yr,
105            mo,
106            day,
107            hr,
108            min,
109            sec,
110            attos: frac,
111            scale: self.target,
112            old_scale: self.scale,
113        }
114    }
115
116    /// Converts a proleptic Gregorian calendar date+time to a Unix timestamp
117    /// (seconds since 1970-01-01 00:00:00).
118    ///
119    /// - Expects **1 based** `mo` and `day`, and **0 based** `hr`, `min`, and `sec`.
120    /// - Does not perform any time scale conversions.
121    /// - Expects pre-clamped values.
122    pub const fn ymd_to_unix_sec(yr: i64, mo: u8, day: u8, hr: u8, min: u8, sec: u8) -> i64 {
123        let jd = Self::ymd_to_jd(yr, mo, day);
124        // 1970-01-01 00:00:00 UTC corresponds to JD 2440588
125        let days_since_1970 = jd.saturating_sub(2440588);
126        let time_of_day = (hr as i64) * 3600 + (min as i64) * 60 + (sec as i64);
127        days_since_1970
128            .saturating_mul(SEC_PER_DAYI64)
129            .saturating_add(time_of_day)
130    }
131
132    /// Converts a Julian Day Number (JD) to a proleptic Gregorian calendar date.
133    ///
134    /// - Returns `(year, month, day)` where `month` ∈ [1, 12] and `day` ∈ [1, 31]
135    ///   (standard 1-based Gregorian values).
136    /// - This is the inverse of [`Dt::ymd_to_jd`](../struct.Dt.html#method.ymd_to_jd).
137    /// - Supports the full `i64` range, including negative years and year zero.
138    pub const fn jd_to_ymd(jd: i64) -> (i64, u8, u8) {
139        let j = jd as i128;
140
141        #[inline]
142        const fn floor_div_pos(a: i128, b: i128) -> i128 {
143            if a >= 0 { a / b } else { (a - (b - 1)) / b }
144        }
145
146        let a = j + 32044;
147        let b = floor_div_pos(4 * a + 3, 146097);
148        let c = a - floor_div_pos(b * 146097, 4);
149        let d = floor_div_pos(4 * c + 3, 1461);
150        let e = c - floor_div_pos(1461 * d, 4);
151        let m = floor_div_pos(5 * e + 2, 153);
152        let day = (e - floor_div_pos(153 * m + 2, 5) + 1) as u8;
153        let mo = (m + 3 - 12 * floor_div_pos(m, 10)) as u8;
154        let yr = b * 100 + d - 4800 + floor_div_pos(m, 10);
155
156        (Dt::i128_to_i64(yr), mo, day)
157    }
158
159    /// Computes the Julian Day Number (JD) for a proleptic Gregorian calendar date at noon UT.
160    /// This is the inverse of [`jd_to_ymd`].
161    ///
162    /// ## Arguments
163    ///
164    /// * `yr`  - Year (any `i64`; proleptic Gregorian)
165    /// * `mo` - Month (**1-based**: `1` = January, `2` = February, ..., `12` = December)
166    /// * `day`   - Day of the month (**1-based**: `1` = first day of the month)
167    ///
168    /// The algorithm matches the standard astronomical convention used throughout the library
169    /// (`ymd_to_jd(2000, 1, 1) == 2451545`).
170    ///
171    /// ## Notes
172    ///
173    /// - This function expects **1 based** `mo` and `day`. Passing `mo = 0` or `day = 0` (or other
174    ///   out-of-range values) will produce incorrect results as this function does not perform
175    ///   value clamping.
176    /// - Does not deal with bad inputs like February with 30 days, does not do any clamping. If you
177    ///   need to sanitize a year, month, day input use
178    ///   [`Dt::clamp_mdhms`](../struct.Dt.html#method.clamp_mdhms) first.
179    /// - The result is the integer JD corresponding to **noon** on the given date.
180    #[inline]
181    pub const fn ymd_to_jd(yr: i64, mo: u8, day: u8) -> i64 {
182        let y = yr as i128;
183        let m = mo as i16;
184        let d = day as i16;
185
186        let a = (14 - m) / 12;
187        let y = y + 4800 - a as i128;
188        let m = m + 12 * a - 3;
189
190        let y4 = y >> 2; // floor(y / 4) — arithmetic shift works for negatives
191
192        // floor(y / 100)
193        let y100 = if y >= 0 { y / 100 } else { (y - 99) / 100 };
194
195        let y400 = y100 >> 2; // floor(y / 400)
196
197        let day_mo = d + (153 * m + 2) / 5;
198        let yr_part = 365 * y + y4 - y100 + y400 - 32045;
199
200        Dt::i128_to_i64(day_mo as i128 + yr_part)
201    }
202
203    /// Creates a **TAI** [`Dt`] from a proleptic gregorian date which is assumed to be on
204    /// the provided time scale.
205    ///
206    /// - Equivalent to converting to `TAI` for the provided date. This means for example that
207    ///   when using `Scale::UTC` leap seconds are potentially added to the returned [`Dt`].
208    /// - The returned [`Dt`] will have its `scale` field set to `TAI` and its `target` field
209    ///   set to the provided time scale argument from this fn. This makes functions such as
210    ///   [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd) more ergonomic.
211    ///
212    /// All input components are clamped to their valid ranges:
213    /// - `mo`   → 1..=12 **1 based**
214    /// - `day`  → 1..=31 **1 based**
215    /// - `hr`   → 0..=23 **0 based**
216    /// - `min`  → 0..=59 **0 based**
217    /// - `sec`  → 0..=60 **0 based** (permits leap seconds)
218    /// - `attos` → 10¹⁸ **0 based** (clamped to under 1 second)
219    ///
220    /// ## Examples
221    ///
222    /// ```rust
223    /// # #[cfg(feature = "jiff-tz")]
224    /// # {
225    /// use deep_time::{Dt, Lang, Scale};
226    ///
227    /// // library zero is 2000-01-01 noon TAI
228    /// let tai = Dt::from_ymd(2000, 1, 1, Scale::TAI, 12, 0, 0, 0);
229    /// assert_eq!(tai, Dt::ZERO);
230    ///
231    /// // utc noon
232    /// let utc = Dt::from_ymd(2000, 1, 1, Scale::UTC, 12, 0, 0, 0);
233    /// // output with timezone requires jiff-tz feature
234    /// // because from_ymd used Scale::UTC, the output is converted
235    /// // back to UTC before being offset by the timezone
236    /// let s = utc.to_str_in_tz("%A, %B %d, %Y %H:%M:%S %Q", "America/New_York", Lang::En).unwrap();
237    /// assert_eq!(s, "Saturday, January 01, 2000 07:00:00 America/New_York");
238    /// # }
239    /// ```
240    ///
241    /// ## See also
242    ///
243    /// - [`Dt::to_ymd`](../struct.Dt.html#method.to_ymd)
244    pub const fn from_ymd(
245        yr: i64,
246        mo: u8,
247        day: u8,
248        scale: Scale,
249        hr: u8,
250        min: u8,
251        sec: u8,
252        attos: u64,
253    ) -> Dt {
254        let (mo, day, hr, min, sec) = Dt::clamp_mdhms(yr, mo, day, hr, min, sec);
255        let attos = Dt::clamp_u64(attos, 0, ATTOS_PER_SEC - 1);
256
257        let sec_is_60 = sec == 60;
258        let s_for_unix = if sec_is_60 { 59 } else { sec };
259
260        let unix_sec = Dt::ymd_to_unix_sec(yr, mo, day, hr, min, s_for_unix);
261        let unix_attos = Dt::sec_to_attos(unix_sec as i128) + (attos as i128);
262
263        if sec_is_60 && scale.uses_leap_seconds() {
264            let t =
265                Dt::from_diff_and_scale(Dt::new(unix_attos, scale, scale), Dt::UNIX_EPOCH, false);
266            let is_leap = match leap_sec(t.add_sec(1).to_sec64(), false) {
267                Some(i) => i.is_leap_sec,
268                None => false,
269            };
270            if is_leap { t.add_sec(1) } else { t }
271        } else {
272            Dt::from_diff_and_scale(Dt::new(unix_attos, scale, scale), Dt::UNIX_EPOCH, false)
273        }
274    }
275
276    /// Computes the Julian Day Number from a Gregorian year and ordinal day-of-year.
277    #[inline]
278    pub const fn ydoy_to_jd(yr: i64, day_of_yr: u16) -> i64 {
279        let jd_jan1 = Self::ymd_to_jd(yr, 1, 1);
280        jd_jan1.saturating_add(day_of_yr as i64 - 1)
281    }
282
283    /// Converts a Julian Day Number to the corresponding weekday number (0 = Sunday … 6 = Saturday).
284    #[inline]
285    pub const fn jd_to_wkday(jd: i64) -> u8 {
286        let rem = ((jd as i128) + 1) % 7;
287        let positive = if rem < 0 { rem + 7 } else { rem };
288        positive as u8
289    }
290
291    /// Computes the Julian Day Number from an ISO week date (Monday-based week).
292    pub const fn iso_wk_to_jd(iso_yr: i64, iso_wk: u8, wkday: Weekday) -> i64 {
293        let jan4_jd = Self::ymd_to_jd(iso_yr, 1, 4);
294        let wd_jan4 = Self::jd_to_wkday(jan4_jd);
295
296        let days_to_monday = {
297            let tmp = (wd_jan4 as i64).saturating_add(6);
298            let rem = tmp % 7;
299            if rem < 0 { rem + 7 } else { rem }
300        };
301
302        let monday_wk1 = jan4_jd.saturating_sub(days_to_monday);
303        let monday_requested =
304            monday_wk1.saturating_add(((iso_wk as i64).saturating_sub(1)).saturating_mul(7));
305
306        monday_requested.saturating_add((wkday.wkday_mon_0_based()) as i64)
307    }
308
309    /// Computes the Julian Day Number from a Sunday-based week-of-year (`%U`).
310    pub const fn wk_sun_to_jd(yr: i64, wk: u8, wkday: Weekday) -> i64 {
311        let jan1_jd = Self::ymd_to_jd(yr, 1, 1);
312        let wd_jan1 = Self::jd_to_wkday(jan1_jd);
313
314        let days_to_first_sunday = ((7u8 - wd_jan1) % 7u8) as i64;
315        let first_sunday_jd = jan1_jd.saturating_add(days_to_first_sunday);
316
317        let sunday_of_wk =
318            first_sunday_jd.saturating_add(((wk as i64).saturating_sub(1)).saturating_mul(7));
319
320        sunday_of_wk.saturating_add(wkday.wkday_sun_0_based() as i64)
321    }
322
323    /// Computes the Julian Day Number from a Monday-based week-of-year (`%W`).
324    pub const fn wk_mon_to_jd(yr: i64, wk: u8, wkday: Weekday) -> i64 {
325        let jan1_jd = Self::ymd_to_jd(yr, 1, 1);
326        let wd_jan1 = Self::jd_to_wkday(jan1_jd);
327
328        let days_to_first_monday = (1i64 - wd_jan1 as i64).rem_euclid(7);
329        let first_monday_jd = jan1_jd.saturating_add(days_to_first_monday);
330
331        let monday_of_wk =
332            first_monday_jd.saturating_add(((wk as i64).saturating_sub(1)).saturating_mul(7));
333
334        monday_of_wk.saturating_add((wkday.wkday_mon_0_based()) as i64)
335    }
336
337    /// Returns `true` if the given year is a Gregorian leap year under proleptic rules.
338    #[inline(always)]
339    pub const fn is_leap_yr(yr: i64) -> bool {
340        (yr & 3 == 0) && ((yr & 15 == 0) || (yr % 25 != 0))
341    }
342
343    /// Returns `true` if the supplied values form a valid proleptic Gregorian calendar date.
344    #[inline]
345    pub const fn is_valid_ymd(yr: i64, mo: u8, day: u8) -> bool {
346        if mo < 1 || mo > 12 || day < 1 {
347            return false;
348        }
349        // 0 = Jan, 1 = Feb, ..., 11 = Dec
350        let days = Self::DAYS_IN_GREGORIAN_MONTHS[(mo - 1) as usize];
351        if mo == 2 && Self::is_leap_yr(yr) {
352            day <= days + 1 // 28 → 29
353        } else {
354            day <= days
355        }
356    }
357
358    /// Returns `true` if the given Gregorian year contains an ISO week 53.
359    pub const fn has_iso_wk_53(yr: i64) -> bool {
360        let jan1_jd = Self::ymd_to_jd(yr, 1, 1);
361        let wd_jan1 = Self::jd_to_wkday(jan1_jd);
362        wd_jan1 == 4 || (Self::is_leap_yr(yr) && wd_jan1 == 3)
363    }
364
365    /// Returns the ordinal day of the year (1-based).
366    ///
367    /// January 1 is day `1`; December 31 is day `365` or `366` (in leap years).
368    /// Uses the proleptic Gregorian calendar.
369    pub const fn day_of_yr(&self, ymd: Option<(i64, u8, u8)>) -> u16 {
370        let (yr, mo, day) = if let Some(ymd) = ymd {
371            ymd
372        } else {
373            let g = self.to_ymd();
374            (g.yr, g.mo, g.day)
375        };
376        Self::_day_of_yr(yr, mo, day)
377    }
378
379    pub(crate) const fn _day_of_yr(yr: i64, mo: u8, day: u8) -> u16 {
380        let jd = Self::ymd_to_jd(yr, mo, day);
381        let jd_jan1 = Self::ymd_to_jd(yr, 1, 1);
382
383        let doy = jd.saturating_sub(jd_jan1).saturating_add(1);
384        doy as u16
385    }
386
387    /// Sunday-based week number (`%U` in strftime).
388    ///
389    /// Range: `0..=53`.
390    /// - Week 0 contains the days *before* the first Sunday of the year.
391    /// - Week 1 begins on the first Sunday of the year.
392    ///
393    /// The optional `ymd` and `doy` arguments are performance optimisations
394    /// (same pattern used throughout the file for `day_of_year`, `to_iso_wk_date`, etc.).
395    /// Pass whichever you already have; the function will use the fastest path.
396    pub const fn wk_sun(&self, ymd: Option<(i64, u8, u8)>, doy: Option<u16>) -> u8 {
397        let (yr, _, _) = if let Some(ymd) = ymd {
398            ymd
399        } else {
400            let g = self.to_ymd();
401            (g.yr, g.mo, g.day)
402        };
403        let doy = if let Some(doy) = doy {
404            doy
405        } else {
406            self.day_of_yr(ymd)
407        };
408        Self::_wk_sun(yr, doy)
409    }
410
411    pub(crate) const fn _wk_sun(yr: i64, doy: u16) -> u8 {
412        let jan1_jd = Self::ymd_to_jd(yr, 1, 1);
413        let wd_jan1 = Self::jd_to_wkday(jan1_jd);
414        let days_to_first_sunday = (7u8 - wd_jan1) % 7u8;
415        let first_sunday_doy = days_to_first_sunday as u16 + 1;
416        if doy < first_sunday_doy {
417            0
418        } else {
419            let days_since_first_sunday = doy.saturating_sub(first_sunday_doy);
420            ((days_since_first_sunday / 7) + 1) as u8
421        }
422    }
423
424    /// Monday-based week number (`%W` in strftime).
425    ///
426    /// Range: `0..=53`.
427    /// - Week 0 contains the days *before* the first Monday of the year.
428    /// - Week 1 begins on the first Monday of the year.
429    ///
430    /// The optional `ymd` and `doy` arguments are performance optimisations
431    /// (same pattern as `wk_sun`, `day_of_yr`, `to_iso_wk_date`, etc.).
432    pub const fn wk_mon(&self, ymd: Option<(i64, u8, u8)>, doy: Option<u16>) -> u8 {
433        let (yr, _, _) = if let Some(ymd) = ymd {
434            ymd
435        } else {
436            let g = self.to_ymd();
437            (g.yr, g.mo, g.day)
438        };
439        let doy = if let Some(doy) = doy {
440            doy
441        } else {
442            self.day_of_yr(ymd)
443        };
444        Self::_wk_mon(yr, doy)
445    }
446
447    pub(crate) const fn _wk_mon(yr: i64, doy: u16) -> u8 {
448        let jan1_jd = Self::ymd_to_jd(yr, 1, 1);
449        let wd_jan1 = Self::jd_to_wkday(jan1_jd);
450        let days_to_first_monday = (1i64 - wd_jan1 as i64).rem_euclid(7);
451        let first_monday_doy = days_to_first_monday as u16 + 1;
452        if doy < first_monday_doy {
453            0
454        } else {
455            let days_since_first_monday = doy.saturating_sub(first_monday_doy);
456            ((days_since_first_monday / 7) + 1) as u8
457        }
458    }
459
460    /// Returns the ISO 8601 week date for this `Dt`.
461    ///
462    /// Returns `(iso_year, iso_week, weekday)` where:
463    /// - `iso_year` is the ISO week year (may differ from the Gregorian year near
464    ///   year boundaries),
465    /// - `iso_week` is the week number in the range `1..=53`,
466    /// - `weekday` is a [`Weekday`] value (Monday-based week).
467    ///
468    /// Follows the ISO 8601 standard: weeks start on Monday and week 1 is the
469    /// week containing January 4.
470    ///
471    /// The optional `ymd` argument is a performance optimization. If provided,
472    /// it is used directly; otherwise [`to_gregorian_ymd`](Self::to_gregorian_ymd)
473    /// is called internally.
474    pub const fn to_iso_wk_date(&self, ymd: Option<(i64, u8, u8)>) -> (i64, u8, Weekday) {
475        let (yr, mo, day) = if let Some(ymd) = ymd {
476            ymd
477        } else {
478            let g = self.to_ymd();
479            (g.yr, g.mo, g.day)
480        };
481        Self::_to_iso_wk_date(yr, mo, day)
482    }
483
484    pub(crate) const fn _to_iso_wk_date(yr: i64, mo: u8, day: u8) -> (i64, u8, Weekday) {
485        let jd = Self::ymd_to_jd(yr, mo, day);
486        let wd = Self::jd_to_wkday(jd);
487        let wd_iso = if wd == 0 { 7 } else { wd };
488
489        let jan4_jd = Self::ymd_to_jd(yr, 1, 4);
490        let wd_jan4 = Self::jd_to_wkday(jan4_jd);
491        let days_to_monday = {
492            let tmp = (wd_jan4 as i64) + 6;
493            let rem = tmp % 7;
494            if rem < 0 { rem + 7 } else { rem }
495        };
496
497        let monday_wk1 = jan4_jd - days_to_monday;
498
499        let days_since = jd - monday_wk1;
500
501        let wk = if days_since < 0 {
502            0u8
503        } else {
504            ((days_since / 7) + 1) as u8
505        };
506
507        let iso_yr = if wk == 0 {
508            yr - 1
509        } else if wk >= 53 && !Self::has_iso_wk_53(yr) {
510            yr + 1
511        } else {
512            yr
513        };
514
515        let iso_wk = if wk == 0 {
516            if Self::has_iso_wk_53(yr - 1) { 53 } else { 52 }
517        } else if (wk == 53 && !Self::has_iso_wk_53(yr)) || wk > 53 {
518            1
519        } else {
520            wk
521        };
522        let wkday_enum = match Weekday::from_monday_1_based(wd_iso) {
523            Some(w) => w,
524            None => Weekday::Monday,
525        };
526
527        (iso_yr, iso_wk, wkday_enum)
528    }
529
530    /// Number of days in a month under proleptic Gregorian rules.
531    #[inline]
532    pub const fn days_in_month(yr: i64, mo: u8) -> u8 {
533        match mo {
534            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
535            4 | 6 | 9 | 11 => 30,
536            2 => {
537                if Self::is_leap_yr(yr) {
538                    29
539                } else {
540                    28
541                }
542            }
543            _ => 0,
544        }
545    }
546
547    /// Clamps month, day, hour, minutes, and seconds values. Clamps days to what is
548    /// correct for that particular propleptic gregorian month.
549    ///
550    /// For example the year 2000 is a leap year, and February in that year has 29 days
551    /// so the days are clamped to 1-29 in that year, but 1-28 in non-leap years.
552    pub const fn clamp_mdhms(
553        yr: i64,
554        mo: u8,
555        day: u8,
556        hr: u8,
557        min: u8,
558        sec: u8,
559    ) -> (u8, u8, u8, u8, u8) {
560        let mo = Self::clamp_u8(mo, 1, 12);
561        let max_day = Self::days_in_month(yr, mo);
562        let day = Self::clamp_u8(day, 1, max_day);
563        let h = Self::clamp_u8(hr, 0, 23);
564        let m = Self::clamp_u8(min, 0, 59);
565        let s = Self::clamp_u8(sec, 0, 60);
566
567        (mo, day, h, m, s)
568    }
569
570    /// Number of days since 1958-01-01 (proleptic Gregorian) → `(year, month, day)`.
571    /// This is the inverse of [`Dt::gregorian_to_days_since_1958`].
572    #[inline]
573    pub const fn days_since_1958_to_gregorian(days_since_epoch: i64) -> (i64, u8, u8) {
574        let jd_1958 = Dt::ymd_to_jd(1958, 1, 1);
575        let jd = jd_1958.saturating_add(days_since_epoch);
576        Dt::jd_to_ymd(jd)
577    }
578
579    /// Inverse of [`Dt::days_since_1958_to_gregorian`].
580    #[inline]
581    pub const fn gregorian_to_days_since_1958(year: i64, month: u8, day: u8) -> i64 {
582        let jd = Dt::ymd_to_jd(year, month, day);
583        let jd_1958 = Dt::ymd_to_jd(1958, 1, 1);
584        jd.saturating_sub(jd_1958)
585    }
586}