ctb_formats_pan/
date.rs

1/* SPDX-License-Identifier: MIT */
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7Permission is hereby granted, free of charge, to any person obtaining a copy of
8this software and associated documentation files (the “Software”), to deal in
9the Software without restriction, including without limitation the rights to
10use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11the Software, and to permit persons to whom the Software is furnished to do so,
12subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24*/
25
26//! Pan date formatting and parsing built on Julian day numbers.
27//! Day format is days between 1/1/4713 BC and the given date, with
28//! adjustment for Gregorian calendar.
29
30#[allow(
31    unused_imports,
32    clippy::wildcard_imports,
33    reason = "Standard workspace module prelude"
34)]
35use crate::utilities::*;
36
37use jiff::Zoned;
38
39/// A Pan date represented as a Julian day number (JDN).
40pub type PanDate = i64;
41
42/// A combined date/time stored as seconds since the Pan superdate epoch.
43pub type PanSuperDate = i64;
44
45const GREGORIAN_START_JDN: PanDate = 2_299_161; // 1582-10-15 (Gregorian)
46const GREGORIAN_START_YMD: (i32, u32, u32) = (1582, 10, 15);
47const JULIAN_END_YMD: (i32, u32, u32) = (1582, 10, 4);
48
49const SUPERDATE_EPOCH_JDN: PanDate = 2_416_481; // 1904-01-01 (Gregorian)
50const SUPERDATE_MIN_YEAR: i32 = 1904;
51const SUPERDATE_MAX_YEAR: i32 = 2040;
52const SUPERDATE_SECONDS_PER_DAY: i64 = 86_400;
53
54const MONTH_NAMES: [&str; 12] = [
55    "January",
56    "February",
57    "March",
58    "April",
59    "May",
60    "June",
61    "July",
62    "August",
63    "September",
64    "October",
65    "November",
66    "December",
67];
68
69const MONTH_ABBR: [&str; 12] = [
70    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
71    "Nov", "Dec",
72];
73
74const WEEKDAY_NAMES: [&str; 7] = [
75    "Sunday",
76    "Monday",
77    "Tuesday",
78    "Wednesday",
79    "Thursday",
80    "Friday",
81    "Saturday",
82];
83
84const WEEKDAY_ABBR: [&str; 7] =
85    ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88enum Calendar {
89    Julian,
90    Gregorian,
91}
92
93/// Converts a year-month-day date into a Pan JDN value. Gregorian calendar
94/// begins at 1582-10-15; dates 1582-10-05..14 are rejected.
95pub fn datevalue(year: i32, month: u32, day: u32) -> Result<PanDate> {
96    let cal = calendar_for_ymd(year, month, day)?;
97    ymd_to_jdn(cal, year, month, day)
98}
99
100/// Converts a Pan JDN value into year, month, and day. Before 1582-10-15 dates
101/// are in Julian calendar.
102pub fn ymd_from_date(date: PanDate) -> Result<(i32, u32, u32)> {
103    jdn_to_ymd(date)
104}
105
106/// Returns today's local date as a Pan JDN value.
107pub fn today() -> Result<PanDate> {
108    let d = Zoned::now().date();
109    datevalue(
110        i32::from(d.year()),
111        u32::try_from(d.month()).context("invalid local month")?,
112        u32::try_from(d.day()).context("invalid local day")?,
113    )
114}
115
116/// Returns the day of week for `date` (Sunday = 0, Saturday = 6).
117pub fn dayofweek(date: PanDate) -> i64 {
118    (date.rem_euclid(7).saturating_add(1)).rem_euclid(7)
119}
120
121/// Returns the day of month for `date`.
122pub fn dayvalue(date: PanDate) -> Result<u32> {
123    let (_y, _m, d) = ymd_from_date(date)?;
124    Ok(d)
125}
126
127/// Returns the month number for `date` (1-12).
128pub fn monthvalue(date: PanDate) -> Result<u32> {
129    let (_y, m, _d) = ymd_from_date(date)?;
130    Ok(m)
131}
132
133/// Returns the year for `date`.
134pub fn yearvalue(date: PanDate) -> Result<i32> {
135    let (y, _m, _d) = ymd_from_date(date)?;
136    Ok(y)
137}
138
139/// Returns the first day of the month containing `date`.
140pub fn month1st(date: PanDate) -> Result<PanDate> {
141    let (y, m, _d) = ymd_from_date(date)?;
142    datevalue(y, m, 1)
143}
144
145/// Returns the number of days in the month containing `date`.
146pub fn monthlength(date: PanDate) -> Result<i64> {
147    let (y, m, _d) = ymd_from_date(date)?;
148    let this = datevalue(y, m, 1)?;
149    let (ny, nm) = add_months_ym(y, m, 1)?;
150    let next = datevalue(ny, nm, 1)?;
151    Ok(next.saturating_sub(this))
152}
153
154/// Adds `offset` months, clamping the day to the new month length.
155pub fn monthmath(date: PanDate, offset: i64) -> Result<PanDate> {
156    let (y, m, d) = ymd_from_date(date)?;
157    let (ty, tm) = add_months_ym(y, m, offset)?;
158    let max_day = month_length_ym(ty, tm)?;
159    let day = if d > max_day { max_day } else { d };
160    datevalue(ty, tm, day)
161}
162
163/// Returns the first day of the quarter containing `date`.
164pub fn quarter1st(date: PanDate) -> Result<PanDate> {
165    let (y, m, _d) = ymd_from_date(date)?;
166    let quarter = (m.saturating_sub(1)) / 3;
167    let qm = quarter.saturating_mul(3).saturating_add(1);
168    datevalue(y, qm, 1)
169}
170
171/// Returns the quarter number (1-4) for `date`.
172pub fn quartervalue(date: PanDate) -> Result<u32> {
173    let (_y, m, _d) = ymd_from_date(date)?;
174    Ok(((m.saturating_sub(1)) / 3).saturating_add(1))
175}
176
177/// Returns the first day of the week containing `date` (Sunday start).
178pub fn week1st(date: PanDate) -> PanDate {
179    let dow = dayofweek(date);
180    date.saturating_sub(dow)
181}
182
183/// Returns the first day of the year containing `date`.
184pub fn year1st(date: PanDate) -> Result<PanDate> {
185    let (y, _m, _d) = ymd_from_date(date)?;
186    datevalue(y, 1, 1)
187}
188
189/// Returns the 1-based week number within the year.
190pub fn weekvalue(date: PanDate) -> Result<i64> {
191    let y1 = year1st(date)?;
192    let delta = date.saturating_sub(y1);
193    Ok(delta.div_euclid(7).saturating_add(1))
194}
195
196/// Formats `date` as `m/d/yy`.
197pub fn datestr(date: PanDate) -> Result<String> {
198    let (y, m, d) = ymd_from_date(date)?;
199    let yy = y.rem_euclid(100);
200    Ok(format!("{m}/{d}/{yy:02}"))
201}
202
203/// Formats `date` as `dd-MON-YYYY`. e.g. 20-APR-2003
204pub fn eurodatestr(date: PanDate) -> Result<String> {
205    let (y, m, d) = ymd_from_date(date)?;
206    let mon = month_abbr(m)?;
207    Ok(format!("{:02}-{}-{:04}", d, mon.to_uppercase(), y))
208}
209
210/// Returns the full weekday name for `date`.
211pub fn daystr(date: PanDate) -> Result<String> {
212    let idx = usize::try_from(dayofweek(date))
213        .context("day of week did not fit into usize")?;
214    let Some(name) = WEEKDAY_NAMES.get(idx) else {
215        bail!("day of week index out of range: {idx}");
216    };
217    Ok((*name).to_string())
218}
219
220/// Formats `date` as `Month ddnth, yyyy`.
221pub fn longdatestr(date: PanDate) -> Result<String> {
222    datepattern(date, "Month ddnth, yyyy")
223}
224
225/// Formats `date` with weekday and long date.
226pub fn completedatestr(date: PanDate) -> Result<String> {
227    let day = daystr(date)?;
228    let long = longdatestr(date)?;
229    Ok(format!("{day}, {long}"))
230}
231
232/// Formats `date` using a Pan date pattern.
233///
234/// Supported tokens include `yy`, `yyyy`, `mm`/`MM`, `mmnth`, `dd`/`DD`,
235/// `ddnth`, `mon`, `month`, `day`, `dayofweek`, `dow`, `ww`, `wwnth`,
236/// `qq`, `qqq`, `qtr`, and `quarter`. Double-quoted literals are copied
237/// verbatim.
238pub fn datepattern(date: PanDate, pattern: &str) -> Result<String> {
239    let (y, m, d) = ymd_from_date(date)?;
240    let yy = y.rem_euclid(100);
241    let dow = dayofweek(date);
242    let qq = ((m.saturating_sub(1)) / 3).saturating_add(1);
243    let ww = weekvalue(date)?;
244
245    let mut out = String::with_capacity(pattern.len().saturating_add(16));
246
247    let mut i = 0usize;
248    while i < pattern.len() {
249        let slice = pattern.get(i..).context("Invalid pattern offset")?;
250
251        // Quoted literal: "..."
252        if slice.starts_with('"') {
253            let rest = pattern
254                .get((i.saturating_add(1))..)
255                .context("Invalid pattern offset")?;
256            let Some(end_rel) = rest.find('"') else {
257                bail!("unterminated quote in date pattern");
258            };
259            let lit = rest.get(..end_rel).context("Invalid quote offset")?;
260            out.push_str(lit);
261            i = i
262                .checked_add(1)
263                .context("pattern index overflow")?
264                .checked_add(end_rel)
265                .context("pattern index overflow")?
266                .checked_add(1)
267                .context("pattern index overflow")?;
268            continue;
269        }
270
271        let Some((tok, style, len)) = match_token(slice) else {
272            let ch = slice
273                .chars()
274                .next()
275                .context("failed to read next pattern char")?;
276            out.push(ch);
277            i = i.saturating_add(ch.len_utf8());
278            continue;
279        };
280
281        apply_token(&mut out, tok, style, y, yy, m, d, dow, qq, ww)?;
282        i = i.saturating_add(len);
283    }
284
285    Ok(out)
286}
287
288#[derive(Debug, Clone, Copy)]
289enum Token {
290    Yy,
291    Yyyy,
292
293    Mm, // month numeric, no leading zero
294    MM, // month numeric, leading zero
295    Mmnth,
296
297    Dd, // day numeric, no leading zero
298    DD, // day numeric, leading zero
299    Ddnth,
300
301    Mon,
302    Month,
303
304    Day,
305    DayOfWeek,
306    Dow,
307
308    Ww,
309    Wwnth,
310
311    Qq,
312    Qqq,     // quarter numeric + 'q'/'Q'
313    Qtr,     // ordinal quarter number (e.g. 2nd)
314    Quarter, // spelled out (e.g. second)
315}
316
317#[derive(Debug, Clone, Copy)]
318enum CaseStyle {
319    Lower,
320    Title,
321    Upper,
322}
323
324fn case_style_from_token(token: &str) -> CaseStyle {
325    let has_alpha = token.chars().any(|c| c.is_ascii_alphabetic());
326    let all_lower = has_alpha
327        && token
328            .chars()
329            .all(|c| !c.is_ascii_alphabetic() || c.is_ascii_lowercase());
330    let all_upper = has_alpha
331        && token
332            .chars()
333            .all(|c| !c.is_ascii_alphabetic() || c.is_ascii_uppercase());
334
335    if all_upper {
336        return CaseStyle::Upper;
337    }
338    if all_lower {
339        return CaseStyle::Lower;
340    }
341    CaseStyle::Title
342}
343
344fn apply_case(s: &str, style: CaseStyle) -> String {
345    match style {
346        CaseStyle::Lower => s.to_lowercase(),
347        CaseStyle::Upper => s.to_uppercase(),
348        CaseStyle::Title => {
349            let mut it = s.chars();
350            let Some(first) = it.next() else {
351                return String::new();
352            };
353            let mut out = String::new();
354            for c in first.to_uppercase() {
355                out.push(c);
356            }
357            out.push_str(&it.as_str().to_lowercase());
358            out
359        }
360    }
361}
362
363fn quarter_word(q: u32) -> Result<&'static str> {
364    match q {
365        1 => Ok("first"),
366        2 => Ok("second"),
367        3 => Ok("third"),
368        4 => Ok("fourth"),
369        _ => bail!("quarter out of range: {q}"),
370    }
371}
372
373fn ordinal_suffix_i64(n: i64) -> &'static str {
374    let d = n.rem_euclid(100);
375    if (11..=13).contains(&d) {
376        return "th";
377    }
378    match n.rem_euclid(10) {
379        1 => "st",
380        2 => "nd",
381        3 => "rd",
382        _ => "th",
383    }
384}
385
386fn match_token(slice: &str) -> Option<(Token, CaseStyle, usize)> {
387    // Longest-first to avoid prefix collisions (e.g. dayofweek vs day).
388    const SPECS: &[(&str, Token, bool)] = &[
389        ("dayofweek", Token::DayOfWeek, false),
390        ("ddnth", Token::Ddnth, false),
391        ("mmnth", Token::Mmnth, false),
392        ("wwnth", Token::Wwnth, false),
393        ("quarter", Token::Quarter, false),
394        ("yyyy", Token::Yyyy, false),
395        ("qqq", Token::Qqq, false),
396        ("qtr", Token::Qtr, false),
397        ("month", Token::Month, false),
398        ("mon", Token::Mon, false),
399        ("dow", Token::Dow, false),
400        ("day", Token::Day, false),
401        ("yy", Token::Yy, false),
402        // Case-sensitive numeric formatting tokens.
403        ("MM", Token::MM, true),
404        ("mm", Token::Mm, true),
405        ("DD", Token::DD, true),
406        ("dd", Token::Dd, true),
407        ("ww", Token::Ww, false),
408        ("qq", Token::Qq, false),
409    ];
410
411    for (raw, tok, case_sensitive) in SPECS {
412        let len = raw.len();
413        if slice.len() < len {
414            continue;
415        }
416        let Some(head) = slice.get(..len) else {
417            continue;
418        };
419        let matches = if *case_sensitive {
420            head == *raw
421        } else {
422            head.eq_ignore_ascii_case(raw)
423        };
424        if matches {
425            return Some((*tok, case_style_from_token(head), len));
426        }
427    }
428
429    None
430}
431
432fn apply_token(
433    out: &mut String,
434    tok: Token,
435    style: CaseStyle,
436    y: i32,
437    yy: i32,
438    m: u32,
439    d: u32,
440    dow: i64,
441    qq: u32,
442    ww: i64,
443) -> Result<()> {
444    use std::fmt::Write;
445    match tok {
446        Token::Yy => {
447            let _ = write!(out, "{yy:02}");
448        }
449        Token::Yyyy => {
450            let _ = write!(out, "{y:04}");
451        }
452
453        Token::Mm => {
454            let _ = write!(out, "{m}");
455        }
456        Token::MM => {
457            let _ = write!(out, "{m:02}");
458        }
459        Token::Mmnth => {
460            let mi = i64::from(m);
461            let _ = write!(out, "{m}{}", ordinal_suffix_i64(mi));
462        }
463
464        Token::Dd => {
465            let _ = write!(out, "{d}");
466        }
467        Token::DD => {
468            let _ = write!(out, "{d:02}");
469        }
470        Token::Ddnth => {
471            let _ = write!(out, "{}{}", d, ordinal_suffix(d));
472        }
473
474        Token::Mon => {
475            let mon = month_abbr(m)?;
476            out.push_str(&apply_case(mon, style));
477        }
478        Token::Month => {
479            let mon = month_name(m)?;
480            out.push_str(&apply_case(mon, style));
481        }
482
483        Token::Day => {
484            let ab = weekday_abbr(dow)?;
485            out.push_str(&apply_case(ab, style));
486        }
487        Token::DayOfWeek => {
488            let full = daystr_from_dow(dow)?;
489            out.push_str(&apply_case(full, style));
490        }
491        Token::Dow => {
492            let _ = write!(out, "{dow}");
493        }
494
495        Token::Ww => {
496            let _ = write!(out, "{ww}");
497        }
498        Token::Wwnth => {
499            let _ = write!(out, "{ww}{}", ordinal_suffix_i64(ww));
500        }
501
502        Token::Qq => {
503            let _ = write!(out, "{qq}");
504        }
505        Token::Qqq => {
506            let qch = match style {
507                CaseStyle::Upper => 'Q',
508                _ => 'q',
509            };
510            let _ = write!(out, "{qq}{qch}");
511        }
512        Token::Qtr => {
513            let qi = i64::from(qq);
514            let _ = write!(out, "{qq}{}", ordinal_suffix_i64(qi));
515        }
516        Token::Quarter => {
517            let w = quarter_word(qq)?;
518            out.push_str(&apply_case(w, style));
519        }
520    }
521
522    Ok(())
523}
524
525fn daystr_from_dow(dow: i64) -> Result<&'static str> {
526    let idx =
527        usize::try_from(dow).context("day of week did not fit into usize")?;
528    let Some(name) = WEEKDAY_NAMES.get(idx) else {
529        bail!("day of week index out of range: {idx}");
530    };
531    Ok(*name)
532}
533
534/// Formats a date with a short, friendly representation.
535/// - Today: "Today"
536/// - Within 6 months: "Wed, Apr 20"
537/// - Older: "4/20/03"
538pub fn naturaldatestr(date: PanDate) -> Result<String> {
539    let t = today()?;
540    naturaldatestr_with_today(date, t)
541}
542
543/// Parses a human-friendly date string into a Pan JDN value.
544pub fn date(text: &str) -> Result<PanDate> {
545    let t = today()?;
546    date_with_today(text, t)
547}
548
549/// Formats `date` relative to the provided `today` reference.
550fn naturaldatestr_with_today(date: PanDate, today: PanDate) -> Result<String> {
551    if date == today {
552        return Ok("Today".to_string());
553    }
554
555    let delta = today.saturating_sub(date);
556    if (0..=180).contains(&delta) {
557        let (_y, m, d) = ymd_from_date(date)?;
558        let w = weekday_abbr(dayofweek(date))?;
559        let mon = month_abbr(m)?;
560        return Ok(format!("{w}, {mon} {d}"));
561    }
562
563    datestr(date)
564}
565
566/// Parses a date string with a provided `today` reference.
567fn date_with_today(text: &str, today: PanDate) -> Result<PanDate> {
568    let raw = text.trim();
569    if raw.is_empty() {
570        bail!("empty date string");
571    }
572
573    // Slash formats: mm/dd/yy or mm/dd/yyyy
574    if raw.contains('/') {
575        let parts: Vec<&str> = raw.split('/').collect();
576        if parts.len() != 3 {
577            bail!("invalid mm/dd/yy format: {raw}");
578        }
579
580        let month = parts
581            .first()
582            .context("Missing month part")?
583            .trim()
584            .parse::<u32>()
585            .context("month")?;
586        let day = parts
587            .get(1)
588            .context("Missing day part")?
589            .trim()
590            .parse::<u32>()
591            .context("day")?;
592        let mut year = parts
593            .get(2)
594            .context("Missing year part")?
595            .trim()
596            .parse::<i32>()
597            .context("year")?;
598        if (0..100).contains(&year) {
599            year = expand_two_digit_year(year)?;
600        }
601
602        return datevalue(year, month, day);
603    }
604
605    // European-ish: dd-MON-YYYY (not documented for `date()`, but useful)
606    if raw.contains('-') {
607        let parts: Vec<&str> = raw.split('-').collect();
608        if parts.len() == 3 {
609            let day = parts
610                .first()
611                .context("Missing day part")?
612                .trim()
613                .parse::<u32>()
614                .context("day")?;
615            let month =
616                parse_month_name(parts.get(1).context("Missing month part")?)?;
617            let year = parts
618                .get(2)
619                .context("Missing year part")?
620                .trim()
621                .parse::<i32>()
622                .context("year")?;
623            return datevalue(year, month, day);
624        }
625    }
626
627    // Normalize for keyword parsing.
628    let lower = raw.to_lowercase();
629    let norm = lower.split_whitespace().collect::<Vec<_>>().join(" ");
630
631    // last/next weekday
632    if let Some(rest) = norm.strip_prefix("last ") {
633        let target = parse_weekday_name(rest)?;
634        let base = week1st(today);
635        let candidate = base.saturating_add(target).saturating_sub(7);
636        return Ok(candidate);
637    }
638    if let Some(rest) = norm.strip_prefix("next ") {
639        let target = parse_weekday_name(rest)?;
640        let base = week1st(today);
641        let candidate = base.saturating_add(target).saturating_add(7);
642        return Ok(candidate);
643    }
644
645    // weekday in current week
646    if let Ok(target) = parse_weekday_name(&norm) {
647        let base = week1st(today);
648        return Ok(base.saturating_add(target));
649    }
650
651    // Month dd, yyyy / Mon dd, yyyy
652    // Accept optional comma after the day.
653    let parts = raw.split_whitespace().collect::<Vec<_>>();
654    if parts.len() >= 3 {
655        let month =
656            parse_month_name(parts.first().context("Missing month part")?)?;
657        let day_str = parts
658            .get(1)
659            .context("Missing day part")?
660            .trim_end_matches(',');
661        let day = day_str.parse::<u32>().context("day")?;
662        let year_str = parts
663            .get(2)
664            .context("Missing year part")?
665            .trim_start_matches(',');
666        let year = year_str.parse::<i32>().context("year")?;
667        return datevalue(year, month, day);
668    }
669
670    bail!("unsupported date format: {raw}");
671}
672
673fn expand_two_digit_year(yy: i32) -> Result<i32> {
674    // Conventional pivot (can be adjusted later if needed).
675    if (0..=69).contains(&yy) {
676        Ok(2000i32.saturating_add(yy))
677    } else if (70..=99).contains(&yy) {
678        Ok(1900i32.saturating_add(yy))
679    } else {
680        bail!("two-digit year out of range: {yy}");
681    }
682}
683
684fn weekday_abbr(dow: i64) -> Result<&'static str> {
685    let idx = usize::try_from(dow).context("weekday did not fit into usize")?;
686    let Some(s) = WEEKDAY_ABBR.get(idx) else {
687        bail!("weekday index out of range: {idx}");
688    };
689    Ok(*s)
690}
691
692fn parse_weekday_name(s: &str) -> Result<i64> {
693    let t = s.trim().to_lowercase();
694    let t = t.as_str();
695
696    for (idx, name) in WEEKDAY_NAMES.iter().enumerate() {
697        if t == name.to_lowercase() {
698            let v = i64::try_from(idx).context("weekday idx")?;
699            return Ok(v);
700        }
701    }
702
703    for (idx, abbr) in WEEKDAY_ABBR.iter().enumerate() {
704        if t == abbr.to_lowercase() {
705            let v = i64::try_from(idx).context("weekday idx")?;
706            return Ok(v);
707        }
708    }
709
710    bail!("unrecognized weekday: {s}");
711}
712
713fn parse_month_name(s: &str) -> Result<u32> {
714    let t = s.trim().trim_end_matches(',').to_lowercase();
715
716    for (i, name) in MONTH_NAMES.iter().enumerate() {
717        if t == name.to_lowercase() {
718            return u32::try_from(i.saturating_add(1)).context("month idx");
719        }
720    }
721    for (i, abbr) in MONTH_ABBR.iter().enumerate() {
722        if t == abbr.to_lowercase() {
723            return u32::try_from(i.saturating_add(1)).context("month idx");
724        }
725    }
726
727    bail!("unrecognized month name: {s}");
728}
729
730fn month_name(month: u32) -> Result<&'static str> {
731    let idx = usize::try_from(month)
732        .context("month did not fit into usize")?
733        .checked_sub(1)
734        .context("month is 0")?;
735    let Some(s) = MONTH_NAMES.get(idx) else {
736        bail!("month out of range: {month}");
737    };
738    Ok(*s)
739}
740
741fn month_abbr(month: u32) -> Result<&'static str> {
742    let idx = usize::try_from(month)
743        .context("month did not fit into usize")?
744        .checked_sub(1)
745        .context("month is 0")?;
746    let Some(s) = MONTH_ABBR.get(idx) else {
747        bail!("month out of range: {month}");
748    };
749    Ok(*s)
750}
751
752fn ordinal_suffix(day: u32) -> &'static str {
753    let d = day % 100;
754    if (11..=13).contains(&d) {
755        return "th";
756    }
757    match day % 10 {
758        1 => "st",
759        2 => "nd",
760        3 => "rd",
761        _ => "th",
762    }
763}
764
765/// Selects the calendar around the Gregorian cutover date.
766fn calendar_for_ymd(year: i32, month: u32, day: u32) -> Result<Calendar> {
767    if (year, month, day) >= GREGORIAN_START_YMD {
768        return Ok(Calendar::Gregorian);
769    }
770    if (year, month, day) <= JULIAN_END_YMD {
771        return Ok(Calendar::Julian);
772    }
773    bail!("invalid date in Gregorian cutover gap: {year}-{month:02}-{day:02}");
774}
775
776/// Converts a year-month-day date to a Julian day number.
777fn ymd_to_jdn(
778    cal: Calendar,
779    year: i32,
780    month: u32,
781    day: u32,
782) -> Result<PanDate> {
783    let y = i64::from(year);
784    let m = i64::from(month);
785    let d = i64::from(day);
786
787    let a = 14_i64.saturating_sub(m).div_euclid(12);
788    let y2 = y.saturating_add(4800).saturating_sub(a);
789    let m2 = m.saturating_add(12_i64.saturating_mul(a)).saturating_sub(3);
790
791    let jdn = match cal {
792        Calendar::Gregorian => d
793            .saturating_add(
794                (153_i64.saturating_mul(m2).saturating_add(2)).div_euclid(5),
795            )
796            .saturating_add(365_i64.saturating_mul(y2))
797            .saturating_add(y2.div_euclid(4))
798            .saturating_sub(y2.div_euclid(100))
799            .saturating_add(y2.div_euclid(400))
800            .saturating_sub(32045),
801        Calendar::Julian => d
802            .saturating_add(
803                (153_i64.saturating_mul(m2).saturating_add(2)).div_euclid(5),
804            )
805            .saturating_add(365_i64.saturating_mul(y2))
806            .saturating_add(y2.div_euclid(4))
807            .saturating_sub(32083),
808    };
809
810    Ok(jdn)
811}
812
813/// Converts a Julian day number into year, month, and day.
814fn jdn_to_ymd(jdn: PanDate) -> Result<(i32, u32, u32)> {
815    if jdn >= GREGORIAN_START_JDN {
816        jdn_to_ymd_gregorian(jdn)
817    } else {
818        jdn_to_ymd_julian(jdn)
819    }
820}
821
822fn jdn_to_ymd_gregorian(jdn: PanDate) -> Result<(i32, u32, u32)> {
823    let a = jdn.saturating_add(32044);
824    let b = (4_i64.saturating_mul(a).saturating_add(3)).div_euclid(146097);
825    let c = a.saturating_sub((146097_i64.saturating_mul(b)).div_euclid(4));
826    let d = (4_i64.saturating_mul(c).saturating_add(3)).div_euclid(1461);
827    let e = c.saturating_sub((1461_i64.saturating_mul(d)).div_euclid(4));
828    let m = (5_i64.saturating_mul(e).saturating_add(2)).div_euclid(153);
829
830    let day = e
831        .saturating_sub(
832            (153_i64.saturating_mul(m).saturating_add(2)).div_euclid(5),
833        )
834        .saturating_add(1);
835    let month = m
836        .saturating_add(3)
837        .saturating_sub(12_i64.saturating_mul(m.div_euclid(10)));
838    let year = 100_i64
839        .saturating_mul(b)
840        .saturating_add(d)
841        .saturating_sub(4800)
842        .saturating_add(m.div_euclid(10));
843
844    let y = i32::try_from(year).context("year did not fit into i32")?;
845    let mo = u32::try_from(month).context("month did not fit into u32")?;
846    let da = u32::try_from(day).context("day did not fit into u32")?;
847    Ok((y, mo, da))
848}
849
850fn jdn_to_ymd_julian(jdn: PanDate) -> Result<(i32, u32, u32)> {
851    let c = jdn.saturating_add(32082);
852    let d = (4_i64.saturating_mul(c).saturating_add(3)).div_euclid(1461);
853    let e = c.saturating_sub((1461_i64.saturating_mul(d)).div_euclid(4));
854    let m = (5_i64.saturating_mul(e).saturating_add(2)).div_euclid(153);
855
856    let day = e
857        .saturating_sub(
858            (153_i64.saturating_mul(m).saturating_add(2)).div_euclid(5),
859        )
860        .saturating_add(1);
861    let month = m
862        .saturating_add(3)
863        .saturating_sub(12_i64.saturating_mul(m.div_euclid(10)));
864    let year = d.saturating_sub(4800).saturating_add(m.div_euclid(10));
865
866    let y = i32::try_from(year).context("year did not fit into i32")?;
867    let mo = u32::try_from(month).context("month did not fit into u32")?;
868    let da = u32::try_from(day).context("day did not fit into u32")?;
869    Ok((y, mo, da))
870}
871
872/// Adds `offset` months to a year-month pair.
873fn add_months_ym(year: i32, month: u32, offset: i64) -> Result<(i32, u32)> {
874    let y = i64::from(year);
875    let m0 = i64::from(month)
876        .checked_sub(1)
877        .context("month out of range")?;
878    let total = y
879        .checked_mul(12)
880        .context("year overflow")?
881        .checked_add(m0)
882        .context("month overflow")?
883        .checked_add(offset)
884        .context("offset overflow")?;
885
886    let ty = total.div_euclid(12);
887    let tm0 = total.rem_euclid(12);
888    let tm = tm0.saturating_add(1);
889
890    let out_y = i32::try_from(ty).context("year did not fit into i32")?;
891    let out_m = u32::try_from(tm).context("month did not fit into u32")?;
892    Ok((out_y, out_m))
893}
894
895/// Returns the month length, honoring the Gregorian cutover.
896fn month_length_ym(year: i32, month: u32) -> Result<u32> {
897    let cal = calendar_for_ymd(year, month, 1)?;
898    let mut len = match month {
899        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
900        4 | 6 | 9 | 11 => 30,
901        2 => {
902            let leap = match cal {
903                Calendar::Gregorian => is_leap_year_gregorian(year),
904                Calendar::Julian => is_leap_year_julian(year),
905            };
906            if leap { 29 } else { 28 }
907        }
908        _ => bail!("month out of range: {month}"),
909    };
910
911    // Account for Gregorian cutover month length when relevant: October 1582
912    // loses 10 calendar dates (5..14) under the historical reform.
913    if (year, month) == (1582, 10) {
914        len = 21;
915    }
916
917    Ok(len)
918}
919
920fn is_leap_year_gregorian(year: i32) -> bool {
921    (year.rem_euclid(4) == 0 && year.rem_euclid(100) != 0)
922        || year.rem_euclid(400) == 0
923}
924
925fn is_leap_year_julian(year: i32) -> bool {
926    year.rem_euclid(4) == 0
927}
928
929/// Combines a date and seconds into a superdate timestamp.
930pub fn superdate(date: PanDate, time: i64) -> Result<PanSuperDate> {
931    let (y, _m, _d) = ymd_from_date(date)?;
932    if !(SUPERDATE_MIN_YEAR..=SUPERDATE_MAX_YEAR).contains(&y) {
933        bail!(
934            "superdate date out of range: {y} (supported {SUPERDATE_MIN_YEAR}..={SUPERDATE_MAX_YEAR})"
935        );
936    }
937    if !(0..SUPERDATE_SECONDS_PER_DAY).contains(&time) {
938        bail!(
939            "superdate time out of range: {time} (expected 0..{SUPERDATE_SECONDS_PER_DAY})"
940        );
941    }
942
943    let days = date
944        .checked_sub(SUPERDATE_EPOCH_JDN)
945        .context("date before superdate epoch")?;
946    let base = days
947        .checked_mul(SUPERDATE_SECONDS_PER_DAY)
948        .context("superdate overflow (days)")?;
949    base.checked_add(time).context("superdate overflow (time)")
950}
951
952/// Extracts the date component from a superdate timestamp.
953pub fn regulardate(number: PanSuperDate) -> Result<PanDate> {
954    let (days, _secs) = split_superdate(number)?;
955    let date = SUPERDATE_EPOCH_JDN
956        .checked_add(days)
957        .context("superdate overflow converting to date")?;
958
959    let (y, _m, _d) = ymd_from_date(date)?;
960    if !(SUPERDATE_MIN_YEAR..=SUPERDATE_MAX_YEAR).contains(&y) {
961        bail!("superdate date out of range after conversion: {y}");
962    }
963
964    Ok(date)
965}
966
967/// Extracts the seconds-since-midnight from a superdate timestamp.
968pub fn regulartime(number: PanSuperDate) -> Result<i64> {
969    let (_days, secs) = split_superdate(number)?;
970    Ok(secs)
971}
972
973/// Formats a superdate as `m/d/yy h:mm AM/PM`.
974pub fn superdatestr(number: PanSuperDate) -> Result<String> {
975    let d = regulardate(number)?;
976    let t = regulartime(number)?;
977    let ds = datestr(d)?;
978    let ts = format_time_ampm(t, false)?;
979    Ok(format!("{ds} {ts}"))
980}
981
982/// Formats a superdate including seconds.
983pub fn superdatesecondsstr(number: PanSuperDate) -> Result<String> {
984    let d = regulardate(number)?;
985    let t = regulartime(number)?;
986    let ds = datestr(d)?;
987    let ts = format_time_ampm(t, true)?;
988    Ok(format!("{ds} {ts}"))
989}
990
991/// Formats a superdate using separate date and time patterns.
992pub fn superdatepattern(
993    number: PanSuperDate,
994    date_pat: &str,
995    time_pat: &str,
996) -> Result<String> {
997    let d = regulardate(number)?;
998    let t = regulartime(number)?;
999    let ds = datepattern(d, date_pat)?;
1000    let ts = super::time::timepattern(t, time_pat)?;
1001    Ok(format!("{ds}{ts}"))
1002}
1003
1004/// Returns the current local time as a superdate timestamp.
1005pub fn supernow() -> Result<PanSuperDate> {
1006    let now = Zoned::now();
1007    let d = now.date();
1008    let t = now.time();
1009
1010    let date = datevalue(
1011        i32::from(d.year()),
1012        u32::try_from(d.month()).context("invalid local month")?,
1013        u32::try_from(d.day()).context("invalid local day")?,
1014    )?;
1015    let secs = i64::from(ctb_utilities::time::seconds_from_midnight(t));
1016    superdate(date, secs)
1017}
1018
1019fn split_superdate(number: PanSuperDate) -> Result<(i64, i64)> {
1020    if number < 0 {
1021        bail!("superdate must be non-negative: {number}");
1022    }
1023    let days = number.div_euclid(SUPERDATE_SECONDS_PER_DAY);
1024    let secs = number.rem_euclid(SUPERDATE_SECONDS_PER_DAY);
1025    Ok((days, secs))
1026}
1027
1028/// Formats seconds since midnight as a 12-hour time with AM/PM.
1029fn format_time_ampm(seconds: i64, include_seconds: bool) -> Result<String> {
1030    if !(0..SUPERDATE_SECONDS_PER_DAY).contains(&seconds) {
1031        bail!(
1032            "time seconds out of range: {seconds} (expected 0..{SUPERDATE_SECONDS_PER_DAY})"
1033        );
1034    }
1035
1036    let h24 = seconds.div_euclid(3600);
1037    let rem = seconds.rem_euclid(3600);
1038    let min = rem.div_euclid(60);
1039    let sec = rem.rem_euclid(60);
1040
1041    let ampm = if h24 >= 12 { "PM" } else { "AM" };
1042    let h12 = match h24.rem_euclid(12) {
1043        0 => 12,
1044        x => x,
1045    };
1046
1047    if include_seconds {
1048        Ok(format!("{h12}:{min:02}:{sec:02} {ampm}"))
1049    } else {
1050        Ok(format!("{h12}:{min:02} {ampm}"))
1051    }
1052}
1053
1054#[cfg(test)]
1055#[allow(
1056    clippy::panic,
1057    clippy::expect_used,
1058    clippy::unwrap_used,
1059    clippy::unwrap_in_result,
1060    clippy::panic_in_result_fn,
1061    clippy::indexing_slicing,
1062    clippy::arithmetic_side_effects,
1063    reason = "Standard repository test boilerplate"
1064)]
1065mod tests {
1066    use super::*;
1067
1068    use ctb_utilities::anyhow::ensure;
1069
1070    #[crate::ctb_test]
1071    fn datevalue_matches_doc_example() -> Result<()> {
1072        // Aug 7, 1991 => 2,448,476.
1073        let n = datevalue(1991, 8, 7)?;
1074        ensure!(n == 2_448_476, "got {n}");
1075        Ok(())
1076    }
1077
1078    #[crate::ctb_test]
1079    fn jdn_roundtrip_ymd() -> Result<()> {
1080        let n = datevalue(2003, 4, 20)?;
1081        let (y, m, d) = ymd_from_date(n)?;
1082        ensure!((y, m, d) == (2003, 4, 20), "got {y}-{m}-{d}");
1083        Ok(())
1084    }
1085
1086    #[crate::ctb_test]
1087    fn dayofweek_known_date() -> Result<()> {
1088        // 2000-01-01 is Saturday.
1089        let n = datevalue(2000, 1, 1)?;
1090        ensure!(dayofweek(n) == 6, "got {}", dayofweek(n));
1091        ensure!(daystr(n)? == "Saturday");
1092        Ok(())
1093    }
1094
1095    #[crate::ctb_test]
1096    fn string_formats_examples() -> Result<()> {
1097        let n = datevalue(2003, 4, 20)?;
1098        ensure!(datestr(n)? == "4/20/03");
1099        ensure!(eurodatestr(n)? == "20-APR-2003");
1100        ensure!(longdatestr(n)? == "April 20th, 2003");
1101        ensure!(
1102            completedatestr(n)? == "Sunday, April 20th, 2003",
1103            "got {}",
1104            completedatestr(n)?
1105        );
1106        Ok(())
1107    }
1108
1109    #[crate::ctb_test]
1110    fn datepattern_documented_example() -> Result<()> {
1111        let n = datevalue(2003, 5, 12)?;
1112        let s = datepattern(n, "Month ddnth, yyyy")?;
1113        ensure!(s == "May 12th, 2003", "got {s}");
1114        Ok(())
1115    }
1116
1117    #[crate::ctb_test]
1118    fn parse_date_slash_and_monthname() -> Result<()> {
1119        let n1 = date_with_today("12/9/1979", datevalue(2024, 1, 1)?)?;
1120        let n2 = datevalue(1979, 12, 9)?;
1121        ensure!(n1 == n2);
1122
1123        let n3 = date_with_today("Apr 20, 2003", datevalue(2024, 1, 1)?)?;
1124        let n4 = datevalue(2003, 4, 20)?;
1125        ensure!(n3 == n4);
1126
1127        let n5 = date_with_today("April 20, 2003", datevalue(2024, 1, 1)?)?;
1128        ensure!(n5 == n4);
1129
1130        Ok(())
1131    }
1132
1133    #[crate::ctb_test]
1134    fn monthmath_clamps_to_last_day() -> Result<()> {
1135        // From docs: March 31 + 1 month => April 30.
1136        let src = datevalue(1997, 3, 31)?;
1137        let dst = monthmath(src, 1)?;
1138        let (y, m, d) = ymd_from_date(dst)?;
1139        ensure!((y, m, d) == (1997, 4, 30), "got {y}-{m}-{d}");
1140        Ok(())
1141    }
1142
1143    #[crate::ctb_test]
1144    fn monthlength_leap_year_behavior() -> Result<()> {
1145        let feb_2000 = datevalue(2000, 2, 10)?;
1146        ensure!(monthlength(feb_2000)? == 29);
1147
1148        let feb_1900 = datevalue(1900, 2, 10)?;
1149        ensure!(monthlength(feb_1900)? == 28);
1150
1151        let feb_1600 = datevalue(1600, 2, 10)?;
1152        ensure!(monthlength(feb_1600)? == 29);
1153
1154        Ok(())
1155    }
1156
1157    #[crate::ctb_test]
1158    fn week_helpers() -> Result<()> {
1159        let weds = datevalue(1995, 7, 12)?;
1160        let sun = week1st(weds);
1161        let (y, m, d) = ymd_from_date(sun)?;
1162        ensure!((y, m, d) == (1995, 7, 9), "got {y}-{m}-{d}");
1163        Ok(())
1164    }
1165
1166    #[crate::ctb_test]
1167    fn parse_weekday_keywords_are_deterministic_with_today() -> Result<()> {
1168        // Today: 2024-01-03 (Wednesday). week1st => 2023-12-31 (Sunday).
1169        let t = datevalue(2024, 1, 3)?;
1170
1171        let tue = date_with_today("Tuesday", t)?;
1172        ensure!(ymd_from_date(tue)? == (2024, 1, 2));
1173
1174        let next_wed = date_with_today("next wed", t)?;
1175        ensure!(ymd_from_date(next_wed)? == (2024, 1, 10));
1176
1177        let last_fri = date_with_today("last fri", t)?;
1178        ensure!(ymd_from_date(last_fri)? == (2023, 12, 29));
1179
1180        Ok(())
1181    }
1182
1183    #[crate::ctb_test]
1184    fn naturaldatestr_rules() -> Result<()> {
1185        let t = datevalue(2024, 1, 3)?;
1186        ensure!(naturaldatestr_with_today(t, t)? == "Today");
1187
1188        let recent = datevalue(2023, 12, 29)?;
1189        let s = naturaldatestr_with_today(recent, t)?;
1190        ensure!(s.starts_with("Fri, "), "got {s}");
1191
1192        let old = datevalue(2023, 1, 1)?;
1193        ensure!(naturaldatestr_with_today(old, t)? == "1/1/23");
1194
1195        let future = datevalue(2024, 2, 1)?;
1196        ensure!(naturaldatestr_with_today(future, t)? == "2/1/24");
1197
1198        Ok(())
1199    }
1200
1201    #[crate::ctb_test]
1202    fn datepattern_mm_mm_dd_dd_casing_and_quotes() -> Result<()> {
1203        let n = datevalue(2003, 4, 20)?;
1204
1205        ensure!(datepattern(n, "mm/dd/yy")? == "4/20/03");
1206        ensure!(datepattern(n, "MM/DD/YY")? == "04/20/03");
1207
1208        ensure!(datepattern(n, "dd-MON-yy")? == "20-APR-03");
1209        ensure!(
1210            datepattern(n, "DayOfWeek, Month ddnth, yyyy")?
1211                == "Sunday, April 20th, 2003"
1212        );
1213        ensure!(datepattern(n, "dayofweek")? == "sunday");
1214        ensure!(datepattern(n, "DOW")? == "0");
1215
1216        let n2 = datevalue(2002, 5, 23)?;
1217        ensure!(
1218            datepattern(n2, "Quarter \"Quarter\" yyyy")?
1219                == "Second Quarter 2002"
1220        );
1221
1222        let n3 = datevalue(2004, 7, 11)?;
1223        ensure!(datepattern(n3, "Qtr \"Qtr\" yyyy")? == "3rd Qtr 2004");
1224
1225        Ok(())
1226    }
1227
1228    #[crate::ctb_test]
1229    fn datepattern_quarter_and_nth_variants() -> Result<()> {
1230        let n = datevalue(2002, 3, 9)?; // Q1
1231        ensure!(datepattern(n, "qqqyy")? == "1q02");
1232
1233        let n2 = datevalue(1867, 3, 1)?;
1234        ensure!(
1235            datepattern(n2, "mmnth \"month of\" yyyy")? == "3rd month of 1867"
1236        );
1237
1238        let n3 = datevalue(2024, 1, 1)?;
1239        ensure!(datepattern(n3, "wwnth")? == "1st");
1240
1241        Ok(())
1242    }
1243
1244    #[crate::ctb_test]
1245    fn superdate_epoch_and_roundtrip() -> Result<()> {
1246        let d0 = datevalue(1904, 1, 1)?;
1247        let n0 = superdate(d0, 0)?;
1248        ensure!(n0 == 0);
1249
1250        ensure!(ymd_from_date(regulardate(0)?)? == (1904, 1, 1));
1251        ensure!(regulartime(0)? == 0);
1252
1253        let d1 = datevalue(1904, 1, 2)?;
1254        let n1 = superdate(d1, 0)?;
1255        ensure!(n1 == SUPERDATE_SECONDS_PER_DAY);
1256
1257        Ok(())
1258    }
1259
1260    #[crate::ctb_test]
1261    fn superdate_roundtrip_date_and_time() -> Result<()> {
1262        let d = datevalue(2003, 4, 20)?;
1263        let t = 9 * 3600 + 56 * 60 + 37;
1264        let n = superdate(d, t)?;
1265
1266        ensure!(regulardate(n)? == d);
1267        ensure!(regulartime(n)? == t);
1268        Ok(())
1269    }
1270
1271    #[crate::ctb_test]
1272    fn superdate_min_and_max_bounds() -> Result<()> {
1273        let min_d = datevalue(1904, 1, 1)?;
1274        ensure!(superdate(min_d, 0)? == 0);
1275
1276        let max_d = datevalue(2040, 12, 31)?;
1277        ensure!(superdate(max_d, SUPERDATE_SECONDS_PER_DAY - 1).is_ok());
1278
1279        ensure!(superdate(min_d, -1).is_err());
1280        ensure!(superdate(min_d, SUPERDATE_SECONDS_PER_DAY).is_err());
1281
1282        ensure!(regulardate(-1).is_err());
1283        ensure!(regulartime(-1).is_err());
1284
1285        Ok(())
1286    }
1287
1288    #[crate::ctb_test]
1289    fn superdate_string_formatting_matches_examples() -> Result<()> {
1290        let d = datevalue(2003, 4, 20)?;
1291        let n = superdate(d, 9 * 3600 + 56 * 60 + 37)?;
1292
1293        ensure!(superdatesecondsstr(n)? == "4/20/03 9:56:37 AM");
1294        ensure!(superdatestr(n)? == "4/20/03 9:56 AM");
1295
1296        Ok(())
1297    }
1298}