Skip to main content

deep_time/dt/
gregorian.rs

1use crate::{ATTOS_PER_SEC, Dt, SEC_PER_DAYI64, Scale, Weekday, YmdHms, YmdHmsRich};
2
3impl Dt {
4    /// Converts a Unix timestamp (seconds since 1970-01-01 00:00:00)
5    /// to a proleptic Gregorian date (year, month, day).
6    #[inline]
7    pub const fn unix_sec_to_ymd(unix_sec: i64) -> (i64, u8, u8) {
8        let days_since_1970 = unix_sec.div_euclid(SEC_PER_DAYI64);
9        // 1970-01-01 00:00:00 is JD 2440588.0
10        let jd = days_since_1970.saturating_add(2440588);
11        Self::jd_to_ymd(jd)
12    }
13
14    /// Returns the full "rich" proleptic Gregorian date and wall-clock time for this instant,
15    /// including all precomputed calendar metadata (ISO week date, day-of-year, multiple
16    /// week-numbering systems, etc.).
17    ///
18    /// This is the "heavy" version of [`to_ymdhms_on`](../struct.Dt.html#method.to_ymdhms_on).
19    /// It performs the same scale conversion but additionally computes and stores every common
20    /// calendar-derived field. This means downstream formatting code does not have to
21    /// re-calculate these numbers for the same object.
22    ///
23    /// The returned [`YmdHmsRich`] has convenient and fast formatter methods for turning
24    /// the object into a datetime - an array of [`u8`] or [`String`](alloc::string::String)
25    /// (requires `"alloc"` feature).
26    ///
27    /// ## Arguments
28    ///
29    /// * `current` — The time scale in which `self` is currently expressed.
30    /// * `new` — The time scale to convert to before creating the rich datetime.
31    ///
32    /// ## See also
33    ///
34    /// * [`Dt::to_ymdhms_rich`](../struct.Dt.html#method.to_ymdhms_rich) — convenience
35    ///   wrapper that always targets `Scale::UTC`.
36    /// * [`Dt::to_ymdhms_on`](../struct.Dt.html#method.to_ymdhms_on) — the lightweight
37    ///   version.
38    /// * [`YmdHmsRich`] — the rich struct type and its accessor methods.
39    /// * [`YmdHmsRich::to_str`](../struct.YmdHmsRich.html#method.to_str) — basically like
40    ///   strftime.
41    ///
42    /// ## What you get in `YmdHmsRich`
43    ///
44    /// In addition to the fields returned by [`to_ymdhms_on`](Self::to_ymdhms_on),
45    /// the returned struct also contains:
46    ///
47    /// - `iso_yr`, `iso_wk`, `iso_wkday` — ISO 8601 week date (Monday-based week)
48    /// - `day_of_yr` — ordinal day of the year (1-based)
49    /// - `wkday` — weekday number (0 = Sunday … 6 = Saturday)
50    /// - `wk_of_yr_sun` — Sunday-based week number (`%U` in strftime, range `0..=53`)
51    /// - `wk_of_yr_mon` — Monday-based week number (`%W` in strftime, range `0..=53`)
52    /// - `scale` — the time scale used for the conversion (`new`)
53    ///
54    /// All other fields (`unix_attosec`, `yr`…`attos`, `offset_sec`, `tz`, `tz_abbrev`)
55    /// are populated exactly as in the lightweight [`YmdHms`] version.
56    ///
57    /// ## Performance note
58    ///
59    /// This function performs several extra calendar calculations (ISO week date,
60    /// day-of-year, both week-numbering systems). If you only need the basic YMDHMS
61    /// components, prefer [`to_ymdhms_on`](Self::to_ymdhms_on) for speed.
62    ///
63    /// ## Examples
64    ///
65    /// ```rust
66    /// use deep_time::{Dt, Scale};
67    ///
68    /// let dt = Dt::from_ymdhms(2024, 6, 15, 12, 30, 45, 0);
69    /// let rich = dt.to_ymdhms_rich_on(Scale::TAI, Scale::UTC);
70    ///
71    /// assert_eq!(rich.yr(), 2024);
72    /// assert_eq!(rich.iso_wk(), 24);           // ISO week 24
73    /// assert_eq!(rich.day_of_yr(), 167);       // June 15 is day 167
74    /// assert_eq!(rich.wkday_sun(), 6);         // Saturday
75    /// ```
76    pub const fn to_ymdhms_rich_on(&self, current: Scale, new: Scale) -> YmdHmsRich {
77        let ymdhms = self.to_ymdhms_on(current, new);
78        let (iso_yr, iso_wk, iso_wkday) =
79            self.to_iso_wk_date(current, Some((ymdhms.yr, ymdhms.mo, ymdhms.day)));
80        let day_of_yr = self.day_of_yr(current, Some((ymdhms.yr, ymdhms.mo, ymdhms.day)));
81        let jd = Self::ymd_to_jd(ymdhms.yr, ymdhms.mo, ymdhms.day);
82        let wkday = Self::jd_to_wkday(jd);
83        let wk_of_yr_sun = self.wk_sun(
84            current,
85            Some((ymdhms.yr, ymdhms.mo, ymdhms.day)),
86            Some(day_of_yr),
87        );
88        let wk_of_yr_mon = self.wk_mon(
89            current,
90            Some((ymdhms.yr, ymdhms.mo, ymdhms.day)),
91            Some(day_of_yr),
92        );
93        ymdhms.to_ymdhms_rich_on(
94            iso_yr,
95            iso_wk,
96            iso_wkday,
97            day_of_yr,
98            wkday,
99            wk_of_yr_sun,
100            wk_of_yr_mon,
101            new,
102        )
103    }
104
105    /// Returns the full "rich" proleptic Gregorian date and wall-clock time for this instant,
106    /// expressed in **UTC**.
107    ///
108    /// This is a convenience wrapper around
109    /// [`to_ymdhms_rich_on`](Self::to_ymdhms_rich_on) that always uses `Scale::UTC`
110    /// as the target scale.
111    ///
112    /// See [`to_ymdhms_rich_on`](Self::to_ymdhms_rich_on) for the full documentation,
113    /// including the list of extra calendar fields that are computed and stored.
114    ///
115    /// ## See also
116    ///
117    /// * [`Dt::to_ymdhms_rich_on`](Self::to_ymdhms_rich_on) — the version that lets
118    ///   you choose the target scale.
119    /// * [`Dt::to_ymdhms`](Self::to_ymdhms) — the lightweight UTC version.
120    #[inline]
121    pub const fn to_ymdhms_rich(&self, current: Scale) -> YmdHmsRich {
122        self.to_ymdhms_rich_on(current, Scale::UTC)
123    }
124
125    /// Returns the proleptic Gregorian date and wall-clock time for this instant,
126    /// interpreted on the `current` time scale and expressed on the `new` time scale.
127    ///
128    /// ## Arguments
129    ///
130    /// * `current` — The time scale in which `self` is currently expressed.
131    /// * `new` — The time scale to convert to before creating the gregorian datetime.
132    ///
133    /// **To note:**
134    ///
135    /// If you created your [`Dt`] via [`Dt::from_ymd`](../struct.Dt.html#method.from_ymd)
136    /// or other similar functions, then these effectively used UTC -> TAI when creating the [`Dt`].
137    ///
138    /// So, if you want to roundtrip when calling this function with such a [`Dt`] you'll have to
139    /// use the args `(Scale::TAI, Scale::UTC)`.
140    ///
141    /// ## Returns
142    ///
143    /// A [`YmdHms`] containing:
144    ///
145    /// - `yr`, `mo`, `day` — proleptic Gregorian calendar date
146    /// - `hr` (0–23), `min` (0–59), `sec` (0–60)
147    /// - `attos` — fractional second in attoseconds (`0 ≤ attos < 10¹⁸`)
148    /// - `unix_attosec` — total attoseconds since the Unix epoch (`1970-01-01 00:00:00 UTC`)
149    ///   when this instant is expressed in the `new` scale
150    ///
151    /// ## Leap-second handling
152    ///
153    /// If `new` is one of the scales that use leap seconds (`UTC`, `UTCSpice`, or `UTCSofa`)
154    /// **and** the instant falls exactly on a leap second, the returned `sec` will be `60`.
155    /// In every other case `sec` is in the range `0..=59`.
156    ///
157    /// The implementation converts internally to TAI before checking leap-second status,
158    /// ensuring correct detection regardless of the input scale.
159    ///
160    /// ## See also
161    ///
162    /// * [`Dt::to_ymdhms`](../struct.Dt.html#method.to_ymdhms) — convenience wrapper
163    ///   that always targets `Scale::UTC`.
164    /// * [`Dt::from_ymdhms_on`](../struct.Dt.html#method.from_ymdhms_on) — the inverse operation.
165    ///
166    /// ## Examples
167    ///
168    /// ```rust
169    /// use deep_time::{Dt, Scale};
170    ///
171    /// // `from_ymdhms` always returns a TAI instant
172    /// let dt = Dt::from_ymdhms(2024, 6, 15, 12, 30, 45, 0);
173    /// let ymd = dt.to_ymdhms_on(Scale::TAI, Scale::UTC);
174    ///
175    /// assert_eq!(ymd.yr(), 2024);
176    /// assert_eq!(ymd.mo(), 6);
177    /// assert_eq!(ymd.day(), 15);
178    /// assert_eq!(ymd.hr(), 12);
179    /// assert_eq!(ymd.min(), 30);
180    /// assert_eq!(ymd.sec(), 45);
181    /// assert!(ymd.attos() == 0);
182    /// ```
183    pub const fn to_ymdhms_on(&self, current: Scale, new: Scale) -> YmdHms {
184        // tai knows whether the seconds lie exactly on a leap second
185        let tai = self.to(current, Scale::TAI);
186        let from_unix_epoch = tai.to_scale_and_then_diff(new, Dt::UNIX_EPOCH);
187
188        let (yr, mo, day) = Self::unix_sec_to_ymd(from_unix_epoch.sec);
189
190        let (hr, min, sec) = if new.uses_leap_seconds() && tai.leap_sec(false).is_leap_sec {
191            (23, 59, 60)
192        } else {
193            let seconds_since_midnight = from_unix_epoch.sec.rem_euclid(SEC_PER_DAYI64);
194            let hr = (seconds_since_midnight / 3600) as u8;
195            let min = ((seconds_since_midnight % 3600) / 60) as u8;
196            let sec = (seconds_since_midnight % 60) as u8;
197            (hr, min, sec)
198        };
199
200        YmdHms {
201            unix_attosec: from_unix_epoch.to_attos(),
202            yr,
203            mo,
204            day,
205            hr,
206            min,
207            sec,
208            attos: from_unix_epoch.attos,
209        }
210    }
211
212    /// Returns the proleptic Gregorian date and wall-clock time for this instant,
213    ///
214    /// - Converts to **UTC** before creating the [`YmdHms`] from whatever the
215    ///   provided `current` [`Scale`] is.
216    /// - See [`Dt::to_ymdhms`](../struct.Dt.html#method.to_ymdhms_on) for more info.
217    #[inline]
218    pub const fn to_ymdhms(&self, current: Scale) -> YmdHms {
219        self.to_ymdhms_on(current, Scale::UTC)
220    }
221
222    /// Converts a proleptic Gregorian calendar date+time to a Unix timestamp
223    /// (seconds since 1970-01-01 00:00:00).
224    ///
225    /// - Expects **1 based** `mo` and `day`, and **0 based** `hr`, `min`, and `sec`.
226    /// - Does not perform any time scale conversions.
227    pub const fn ymdhms_to_unix_sec(yr: i64, mo: u8, day: u8, hr: u8, min: u8, sec: u8) -> i64 {
228        let (mo, day, hr, min, sec) = Self::clamp_mdhms(mo, day, hr, min, sec);
229        let jd = Self::ymd_to_jd(yr, mo, day);
230        // 1970-01-01 00:00:00 UTC corresponds to JD 2440588
231        let days_since_1970 = jd.saturating_sub(2440588);
232        let time_of_day = (hr as i64) * 3600 + (min as i64) * 60 + (sec as i64);
233        days_since_1970
234            .saturating_mul(SEC_PER_DAYI64)
235            .saturating_add(time_of_day)
236    }
237
238    /// Converts a Julian Day Number (JD) to a proleptic Gregorian calendar date.
239    ///
240    /// - Returns `(year, month, day)` where `month` ∈ [1, 12] and `day` ∈ [1, 31]
241    ///   (standard 1-based Gregorian values).
242    /// - This is the inverse of [`Dt::ymd_to_jd`](../struct.Dt.html#method.ymd_to_jd).
243    /// - Supports the full `i64` range, including negative years and year zero.
244    pub const fn jd_to_ymd(jd: i64) -> (i64, u8, u8) {
245        let j = jd as i128;
246
247        #[inline]
248        const fn floor_div_pos(a: i128, b: i128) -> i128 {
249            if a >= 0 { a / b } else { (a - (b - 1)) / b }
250        }
251
252        let a = j + 32044;
253        let b = floor_div_pos(4 * a + 3, 146097);
254        let c = a - floor_div_pos(b * 146097, 4);
255        let d = floor_div_pos(4 * c + 3, 1461);
256        let e = c - floor_div_pos(1461 * d, 4);
257        let m = floor_div_pos(5 * e + 2, 153);
258        let day = (e - floor_div_pos(153 * m + 2, 5) + 1) as u8;
259        let mo = (m + 3 - 12 * floor_div_pos(m, 10)) as u8;
260        let yr = b * 100 + d - 4800 + floor_div_pos(m, 10);
261
262        (Dt::clamp_i128_to_i64(yr), mo, day)
263    }
264
265    /// Computes the Julian Day Number (JD) for a proleptic Gregorian calendar date at noon UT.
266    /// This is the inverse of [`jd_to_ymd`].
267    ///
268    /// ## Arguments
269    ///
270    /// * `yr`  - Year (any `i64`; proleptic Gregorian)
271    /// * `mo` - Month (**1-based**: `1` = January, `2` = February, ..., `12` = December)
272    /// * `day`   - Day of the month (**1-based**: `1` = first day of the month)
273    ///
274    /// The algorithm matches the standard astronomical convention used throughout the library
275    /// (`ymd_to_jd(2000, 1, 1) == 2451545`).
276    ///
277    /// ## Notes
278    ///
279    /// - This function expects **1 based** `mo` and `day`. Passing `mo = 0` or `day = 0` (or other
280    ///   out-of-range values) will produce incorrect results as this function does not perform
281    ///   value clamping.
282    /// - The result is the integer JD corresponding to **noon** on the given date.
283    #[inline]
284    pub const fn ymd_to_jd(yr: i64, mo: u8, day: u8) -> i64 {
285        let y = yr as i128;
286        let m = mo as i16;
287        let d = day as i16;
288
289        let a = (14 - m) / 12;
290        let y = y + 4800 - a as i128;
291        let m = m + 12 * a - 3;
292
293        let y4 = y >> 2; // floor(y / 4) — arithmetic shift works for negatives
294
295        // floor(y / 100)
296        let y100 = if y >= 0 { y / 100 } else { (y - 99) / 100 };
297
298        let y400 = y100 >> 2; // floor(y / 400)
299
300        let day_mo = d + (153 * m + 2) / 5;
301        let yr_part = 365 * y + y4 - y100 + y400 - 32045;
302
303        Dt::clamp_i128_to_i64(day_mo as i128 + yr_part)
304    }
305
306    /// Returns `true` if the given year is a Gregorian leap year under proleptic rules.
307    #[inline]
308    pub const fn is_leap_yr(yr: i64) -> bool {
309        yr % 4 == 0 && (yr % 100 != 0 || yr % 400 == 0)
310    }
311
312    /// Creates a TAI [`Dt`] from a proleptic gregorian date which is assumed to be on
313    /// the provided time scale.
314    ///
315    /// - Equivalent to [`Dt::from`](../struct.Dt.html#method.from) for the provided date.
316    /// - Returned [`Dt`] will be on the **TAI** time scale.
317    ///
318    /// All input components are clamped to their valid ranges:
319    /// - `mo`   → 1..=12 **1 based**
320    /// - `day`  → 1..=31 **1 based**
321    /// - `hr`   → 0..=23 **0 based**
322    /// - `min`  → 0..=59 **0 based**
323    /// - `sec`  → 0..=60 **0 based** (permits leap seconds)
324    /// - `attos` → values ≥ 10¹⁸ are carried into the seconds field
325    ///
326    /// ### Notes:
327    ///
328    /// - Does not perform validation on leap seconds. If 60 seconds are
329    ///   provided then an extra second will be added to the resulting [`Dt`].
330    pub const fn from_ymdhms_on(
331        yr: i64,
332        mo: u8,
333        day: u8,
334        hr: u8,
335        min: u8,
336        sec: u8,
337        attos: u64,
338        scale: Scale,
339    ) -> Self {
340        let (mo, day, hr, min, sec) = Self::clamp_mdhms(mo, day, hr, min, sec);
341        let carried_sec = (attos / ATTOS_PER_SEC) as i64;
342        let final_attos = attos % ATTOS_PER_SEC;
343
344        let is_exact_leap_second = sec == 60 && carried_sec == 0;
345        let s_for_unix = if is_exact_leap_second { 59 } else { sec };
346
347        let civil_unix_sec =
348            Self::ymdhms_to_unix_sec(yr, mo, day, hr, min, s_for_unix) + carried_sec;
349
350        let tp =
351            Self::from_diff_and_scale(Dt::new(civil_unix_sec, final_attos), Dt::UNIX_EPOCH, scale);
352        if is_exact_leap_second {
353            Dt::new(tp.sec.saturating_add(1), tp.attos)
354        } else {
355            tp
356        }
357    }
358
359    /// Creates a TAI [`Dt`] from a proleptic gregorian date which is assumed to be on
360    /// the provided time scale.
361    ///
362    /// See [`Dt::from_ymdhms_on`](../struct.Dt.html#method.from_ymdhms_on).
363    #[inline]
364    pub const fn from_ymd_on(yr: i64, mo: u8, day: u8, scale: Scale) -> Self {
365        Dt::from_ymdhms_on(yr, mo, day, 0, 0, 0, 0, scale)
366    }
367
368    /// Creates a TAI [`Dt`] from a proleptic gregorian **UTC** date.
369    ///
370    /// See [`Dt::from_ymdhms_on`](../struct.Dt.html#method.from_ymdhms_on).
371    #[inline]
372    pub const fn from_ymdhms(
373        yr: i64,
374        mo: u8,
375        day: u8,
376        hr: u8,
377        min: u8,
378        sec: u8,
379        attos: u64,
380    ) -> Self {
381        Dt::from_ymdhms_on(yr, mo, day, hr, min, sec, attos, Scale::UTC)
382    }
383
384    /// Creates a TAI [`Dt`] from a proleptic gregorian **UTC** date.
385    ///
386    /// See [`Dt::from_ymdhms_on`](../struct.Dt.html#method.from_ymdhms_on).
387    #[inline]
388    pub const fn from_ymd(yr: i64, mo: u8, day: u8) -> Self {
389        Dt::from_ymdhms_on(yr, mo, day, 0, 0, 0, 0, Scale::UTC)
390    }
391
392    /// Computes the Julian Day Number from a Gregorian year and ordinal day-of-year.
393    #[inline]
394    pub const fn ydoy_to_jd(yr: i64, day_of_yr: u16) -> i64 {
395        let jd_jan1 = Self::ymd_to_jd(yr, 1, 1);
396        jd_jan1.saturating_add(day_of_yr as i64 - 1)
397    }
398
399    /// Converts a Julian Day Number to the corresponding weekday number (0 = Sunday … 6 = Saturday).
400    #[inline]
401    pub const fn jd_to_wkday(jd: i64) -> u8 {
402        let rem = ((jd as i128) + 1) % 7;
403        let positive = if rem < 0 { rem + 7 } else { rem };
404        positive as u8
405    }
406
407    /// Computes the Julian Day Number from an ISO week date (Monday-based week).
408    pub const fn ymd_to_jd_from_iso_wk(iso_yr: i64, iso_wk: u8, wkday: Weekday) -> i64 {
409        let jan4_jd = Self::ymd_to_jd(iso_yr, 1, 4);
410        let wd_jan4 = Self::jd_to_wkday(jan4_jd);
411
412        let days_to_monday = {
413            let tmp = (wd_jan4 as i64).saturating_add(6);
414            let rem = tmp % 7;
415            if rem < 0 { rem + 7 } else { rem }
416        };
417
418        let monday_wk1 = jan4_jd.saturating_sub(days_to_monday);
419        let monday_requested =
420            monday_wk1.saturating_add(((iso_wk as i64).saturating_sub(1)).saturating_mul(7));
421
422        monday_requested.saturating_add((wkday.wk_mon() - 1) as i64)
423    }
424
425    /// Computes the Julian Day Number from a Sunday-based week-of-year (`%U`).
426    pub const fn ymd_to_jd_from_wk_sun(yr: i64, wk: u8, wkday: Weekday) -> i64 {
427        let jan1_jd = Self::ymd_to_jd(yr, 1, 1);
428        let wd_jan1 = Self::jd_to_wkday(jan1_jd);
429
430        let days_to_first_sunday = ((7u8 - wd_jan1) % 7u8) as i64;
431        let first_sunday_jd = jan1_jd.saturating_add(days_to_first_sunday);
432
433        let sunday_of_wk =
434            first_sunday_jd.saturating_add(((wk as i64).saturating_sub(1)).saturating_mul(7));
435
436        sunday_of_wk.saturating_add(wkday.wk_sun() as i64)
437    }
438
439    /// Computes the Julian Day Number from a Monday-based week-of-year (`%W`).
440    pub const fn ymd_to_jd_from_wk_mon(yr: i64, wk: u8, wkday: Weekday) -> i64 {
441        let jan1_jd = Self::ymd_to_jd(yr, 1, 1);
442        let wd_jan1 = Self::jd_to_wkday(jan1_jd);
443
444        let days_to_first_monday = (1i64 - wd_jan1 as i64).rem_euclid(7);
445        let first_monday_jd = jan1_jd.saturating_add(days_to_first_monday);
446
447        let monday_of_wk =
448            first_monday_jd.saturating_add(((wk as i64).saturating_sub(1)).saturating_mul(7));
449
450        monday_of_wk.saturating_add((wkday.wk_mon() - 1) as i64)
451    }
452
453    /// Returns `true` if the supplied values form a valid proleptic Gregorian calendar date.
454    pub const fn is_valid_ymd(yr: i64, mo: u8, day: u8) -> bool {
455        if mo < 1 || mo > 12 || day < 1 {
456            return false;
457        }
458        let days = match mo {
459            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31u8,
460            4 | 6 | 9 | 11 => 30u8,
461            2 => {
462                if Self::is_leap_yr(yr) {
463                    29
464                } else {
465                    28
466                }
467            }
468            _ => return false,
469        };
470        day <= days
471    }
472
473    /// Returns `true` if the given Gregorian year contains an ISO week 53.
474    pub const fn has_iso_wk_53(yr: i64) -> bool {
475        let jan1_jd = Self::ymd_to_jd(yr, 1, 1);
476        let wd_jan1 = Self::jd_to_wkday(jan1_jd);
477        wd_jan1 == 4 || (Self::is_leap_yr(yr) && wd_jan1 == 3)
478    }
479
480    /// Returns the ordinal day of the year (1-based).
481    ///
482    /// January 1 is day `1`; December 31 is day `365` or `366` (in leap years).
483    /// Uses the proleptic Gregorian calendar.
484    pub const fn day_of_yr(&self, current: Scale, ymd: Option<(i64, u8, u8)>) -> u16 {
485        let (yr, month, day) = if let Some(ymd) = ymd {
486            ymd
487        } else {
488            let g = self.to_ymdhms(current);
489            (g.yr, g.mo, g.day)
490        };
491        let jd = Self::ymd_to_jd(yr, month, day);
492        let jd_jan1 = Self::ymd_to_jd(yr, 1, 1);
493
494        let doy = jd.saturating_sub(jd_jan1).saturating_add(1);
495        doy as u16
496    }
497
498    /// Sunday-based week number (`%U` in strftime).
499    ///
500    /// Range: `0..=53`.
501    /// - Week 0 contains the days *before* the first Sunday of the year.
502    /// - Week 1 begins on the first Sunday of the year.
503    ///
504    /// The optional `ymd` and `doy` arguments are performance optimisations
505    /// (same pattern used throughout the file for `day_of_year`, `to_iso_wk_date`, etc.).
506    /// Pass whichever you already have; the function will use the fastest path.
507    pub const fn wk_sun(&self, current: Scale, ymd: Option<(i64, u8, u8)>, doy: Option<u16>) -> u8 {
508        let (yr, _, _) = if let Some(ymd) = ymd {
509            ymd
510        } else {
511            let g = self.to_ymdhms(current);
512            (g.yr, g.mo, g.day)
513        };
514        let doy = if let Some(doy) = doy {
515            doy
516        } else {
517            self.day_of_yr(current, ymd)
518        };
519        let jan1_jd = Self::ymd_to_jd(yr, 1, 1);
520        let wd_jan1 = Self::jd_to_wkday(jan1_jd);
521        let days_to_first_sunday = (7u8 - wd_jan1) % 7u8;
522        let first_sunday_doy = days_to_first_sunday as u16 + 1;
523        if doy < first_sunday_doy {
524            0
525        } else {
526            let days_since_first_sunday = doy.saturating_sub(first_sunday_doy);
527            ((days_since_first_sunday / 7) + 1) as u8
528        }
529    }
530
531    /// Monday-based week number (`%W` in strftime).
532    ///
533    /// Range: `0..=53`.
534    /// - Week 0 contains the days *before* the first Monday of the year.
535    /// - Week 1 begins on the first Monday of the year.
536    ///
537    /// The optional `ymd` and `doy` arguments are performance optimisations
538    /// (same pattern as `wk_sun`, `day_of_yr`, `to_iso_wk_date`, etc.).
539    pub const fn wk_mon(&self, current: Scale, ymd: Option<(i64, u8, u8)>, doy: Option<u16>) -> u8 {
540        let (yr, _, _) = if let Some(ymd) = ymd {
541            ymd
542        } else {
543            let g = self.to_ymdhms(current);
544            (g.yr, g.mo, g.day)
545        };
546        let doy = if let Some(doy) = doy {
547            doy
548        } else {
549            self.day_of_yr(current, ymd)
550        };
551        let jan1_jd = Self::ymd_to_jd(yr, 1, 1);
552        let wd_jan1 = Self::jd_to_wkday(jan1_jd);
553        let days_to_first_monday = (1i64 - wd_jan1 as i64).rem_euclid(7);
554        let first_monday_doy = days_to_first_monday as u16 + 1;
555        if doy < first_monday_doy {
556            0
557        } else {
558            let days_since_first_monday = doy.saturating_sub(first_monday_doy);
559            ((days_since_first_monday / 7) + 1) as u8
560        }
561    }
562
563    /// Returns the ISO 8601 week date for this `Dt`.
564    ///
565    /// Returns `(iso_year, iso_week, weekday)` where:
566    /// - `iso_year` is the ISO week year (may differ from the Gregorian year near
567    ///   year boundaries),
568    /// - `iso_week` is the week number in the range `1..=53`,
569    /// - `weekday` is a [`Weekday`] value (Monday-based week).
570    ///
571    /// Follows the ISO 8601 standard: weeks start on Monday and week 1 is the
572    /// week containing January 4.
573    ///
574    /// The optional `ymd` argument is a performance optimization. If provided,
575    /// it is used directly; otherwise [`to_gregorian_ymd`](Self::to_gregorian_ymd)
576    /// is called internally.
577    pub const fn to_iso_wk_date(
578        &self,
579        current: Scale,
580        ymd: Option<(i64, u8, u8)>,
581    ) -> (i64, u8, Weekday) {
582        let (yr, month, day) = if let Some(ymd) = ymd {
583            ymd
584        } else {
585            let g = self.to_ymdhms(current);
586            (g.yr, g.mo, g.day)
587        };
588        let jd = Self::ymd_to_jd(yr, month, day);
589        let wd = Self::jd_to_wkday(jd);
590        let wd_iso = if wd == 0 { 7 } else { wd };
591
592        let jan4_jd = Self::ymd_to_jd(yr, 1, 4);
593        let wd_jan4 = Self::jd_to_wkday(jan4_jd);
594        let days_to_monday = {
595            let tmp = (wd_jan4 as i64) + 6;
596            let rem = tmp % 7;
597            if rem < 0 { rem + 7 } else { rem }
598        };
599
600        let monday_wk1 = jan4_jd - days_to_monday;
601
602        let days_since = jd - monday_wk1;
603
604        let wk = if days_since < 0 {
605            0u8
606        } else {
607            ((days_since / 7) + 1) as u8
608        };
609
610        let iso_yr = if wk == 0 {
611            yr - 1
612        } else if wk >= 53 && !Self::has_iso_wk_53(yr) {
613            yr + 1
614        } else {
615            yr
616        };
617
618        let iso_wk = if wk == 0 {
619            if Self::has_iso_wk_53(yr - 1) { 53 } else { 52 }
620        } else if (wk == 53 && !Self::has_iso_wk_53(yr)) || wk > 53 {
621            1
622        } else {
623            wk
624        };
625        let wkday_enum = match Weekday::from_monday_one_offset(wd_iso) {
626            Some(w) => w,
627            None => Weekday::Monday,
628        };
629
630        (iso_yr, iso_wk, wkday_enum)
631    }
632
633    pub(crate) const fn clamp_mdhms(
634        mo: u8,
635        day: u8,
636        hr: u8,
637        min: u8,
638        sec: u8,
639    ) -> (u8, u8, u8, u8, u8) {
640        let mo = Self::clamp_u8(mo, 1, 12);
641        let day = Self::clamp_u8(day, 1, 31);
642        let h = Self::clamp_u8(hr, 0, 23);
643        let m = Self::clamp_u8(min, 0, 59);
644        let s = Self::clamp_u8(sec, 0, 60);
645
646        (mo, day, h, m, s)
647    }
648}