use crate::errors::ValidationError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Weekday {
Mon,
Tue,
Wed,
Thu,
Fri,
Sat,
Sun,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Date {
year: i32,
month: u8,
day: u8,
}
impl Date {
pub const MIN_YEAR: i32 = 1583;
pub const MAX_YEAR: i32 = 9999;
pub fn ymd(year: i32, month: u8, day: u8) -> Result<Self, ValidationError> {
if year < Self::MIN_YEAR {
return Err(ValidationError::OutOfRange {
what: "year < 1583",
});
}
if year > Self::MAX_YEAR {
return Err(ValidationError::OutOfRange {
what: "year > 9999",
});
}
if !(1..=12).contains(&month) {
return Err(ValidationError::InvalidDate {
rule: "month-out-of-range",
});
}
let dim = Self::days_in_month(year, month);
if !(1..=dim).contains(&day) {
return Err(ValidationError::InvalidDate {
rule: "day-out-of-range",
});
}
Ok(Self { year, month, day })
}
#[must_use]
pub const fn ymd_unchecked(year: i32, month: u8, day: u8) -> Self {
Self { year, month, day }
}
#[must_use]
#[inline]
pub const fn year(&self) -> i32 {
self.year
}
#[must_use]
#[inline]
pub const fn month(&self) -> u8 {
self.month
}
#[must_use]
#[inline]
pub const fn day(&self) -> u8 {
self.day
}
#[must_use]
#[inline]
pub const fn is_leap_year(year: i32) -> bool {
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
#[must_use]
#[inline]
pub const fn days_in_month(year: i32, month: u8) -> u8 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => {
if Self::is_leap_year(year) {
29
} else {
28
}
}
_ => 0,
}
}
#[inline]
#[allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_lossless
)]
const fn to_civil_days(year: i32, month: u8, day: u8) -> i64 {
let y = year as i64 - if month <= 2 { 1 } else { 0 };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = (y - era * 400) as u32; let m = month as u32;
let m_shift = if m > 2 { m - 3 } else { m + 9 };
let doy = (153 * m_shift + 2) / 5 + (day as u32) - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; era * 146_097 + doe as i64 - 719_468
}
#[inline]
#[allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_lossless
)]
const fn from_civil_days(z: i64) -> Self {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u32; let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = (doy - (153 * mp + 2) / 5 + 1) as u8; let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u8; let year = (y + if m <= 2 { 1 } else { 0 }) as i32;
Self {
year,
month: m,
day: d,
}
}
#[must_use]
pub fn day_of_week(self) -> Weekday {
let z = Self::to_civil_days(self.year, self.month, self.day);
let idx = (z + 3).rem_euclid(7);
match idx {
0 => Weekday::Mon,
1 => Weekday::Tue,
2 => Weekday::Wed,
3 => Weekday::Thu,
4 => Weekday::Fri,
5 => Weekday::Sat,
_ => Weekday::Sun,
}
}
#[must_use]
pub fn add_days(self, days: i32) -> Self {
let z = Self::to_civil_days(self.year, self.month, self.day) + i64::from(days);
Self::from_civil_days(z)
}
#[must_use]
pub fn add_months_eom_aware(self, months: i32) -> Self {
let total = i64::from(self.year) * 12 + (i64::from(self.month) - 1) + i64::from(months);
let new_year_i64 = total.div_euclid(12);
let new_month_i64 = total.rem_euclid(12) + 1;
let new_year = i32::try_from(new_year_i64).unwrap_or(self.year);
let new_month = u8::try_from(new_month_i64).unwrap_or(self.month);
let dim = Self::days_in_month(new_year, new_month);
let new_day = if self.day < dim { self.day } else { dim };
Self::ymd_unchecked(new_year, new_month, new_day)
}
pub fn nth_weekday_of_month(
year: i32,
month: u8,
n: u8,
weekday: Weekday,
) -> Result<Self, ValidationError> {
if !(1..=5).contains(&n) {
return Err(ValidationError::OutOfRange {
what: "n must be 1..=5",
});
}
let first = Self::ymd(year, month, 1)?;
let first_wd = first.day_of_week();
let offset = (weekday_index(weekday) + 7 - weekday_index(first_wd)) % 7;
let day_in_month = 1 + offset + (i32::from(n) - 1) * 7;
let dim = i32::from(Self::days_in_month(year, month));
if day_in_month > dim {
return Err(ValidationError::OutOfRange {
what: "nth weekday does not exist in this month",
});
}
let day = u8::try_from(day_in_month).unwrap_or(1);
Ok(Self { year, month, day })
}
#[must_use]
#[allow(
clippy::many_single_char_names,
clippy::cast_possible_truncation,
clippy::cast_sign_loss
)]
pub fn easter_sunday(year: i32) -> Self {
let y = year;
let a = y % 19;
let b = y / 100;
let c = y % 100;
let d = b / 4;
let e = b % 4;
let f = (b + 8) / 25;
let g = (b - f + 1) / 3;
let h = (19 * a + b - d - g + 15) % 30;
let i = c / 4;
let k = c % 4;
let l = (32 + 2 * e + 2 * i - h - k) % 7;
let m = (a + 11 * h + 22 * l) / 451;
let month_num = (h + l - 7 * m + 114) / 31; let day_num = ((h + l - 7 * m + 114) % 31) + 1;
Self {
year: y,
month: month_num as u8,
day: day_num as u8,
}
}
#[must_use]
pub fn days_between(self, other: Self) -> i32 {
let a = Self::to_civil_days(self.year, self.month, self.day);
let b = Self::to_civil_days(other.year, other.month, other.day);
i32::try_from(b - a).unwrap_or(i32::MAX)
}
}
#[inline]
const fn weekday_index(w: Weekday) -> i32 {
match w {
Weekday::Mon => 0,
Weekday::Tue => 1,
Weekday::Wed => 2,
Weekday::Thu => 3,
Weekday::Fri => 4,
Weekday::Sat => 5,
Weekday::Sun => 6,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn leap_year_known_anchors() {
assert!(!Date::is_leap_year(1900));
assert!(Date::is_leap_year(2000));
assert!(Date::is_leap_year(2004));
assert!(Date::is_leap_year(2020));
assert!(Date::is_leap_year(2024));
assert!(!Date::is_leap_year(2025));
assert!(!Date::is_leap_year(2026));
assert!(!Date::is_leap_year(2100));
assert!(Date::is_leap_year(2400));
}
#[test]
fn days_in_month_non_leap() {
let expected = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
for (m, &d) in (1..=12).zip(expected.iter()) {
assert_eq!(Date::days_in_month(2025, m), d, "month {m} non-leap");
}
}
#[test]
fn days_in_month_leap() {
let expected = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
for (m, &d) in (1..=12).zip(expected.iter()) {
assert_eq!(Date::days_in_month(2024, m), d, "month {m} leap");
}
}
#[test]
fn days_in_month_invalid_month_is_zero() {
assert_eq!(Date::days_in_month(2026, 0), 0);
assert_eq!(Date::days_in_month(2026, 13), 0);
}
#[test]
fn ymd_accepts_boundary_years() {
assert!(Date::ymd(1583, 1, 1).is_ok());
assert!(Date::ymd(9999, 12, 31).is_ok());
}
#[test]
fn ymd_rejects_year_below_min() {
assert_eq!(
Date::ymd(1582, 1, 1),
Err(ValidationError::OutOfRange {
what: "year < 1583",
})
);
}
#[test]
fn ymd_rejects_year_above_max() {
assert_eq!(
Date::ymd(10_000, 1, 1),
Err(ValidationError::OutOfRange {
what: "year > 9999",
})
);
}
#[test]
fn ymd_rejects_month_zero_and_thirteen() {
assert_eq!(
Date::ymd(2026, 0, 1),
Err(ValidationError::InvalidDate {
rule: "month-out-of-range",
})
);
assert_eq!(
Date::ymd(2026, 13, 1),
Err(ValidationError::InvalidDate {
rule: "month-out-of-range",
})
);
}
#[test]
fn ymd_rejects_day_zero_and_overflow() {
assert_eq!(
Date::ymd(2026, 1, 0),
Err(ValidationError::InvalidDate {
rule: "day-out-of-range",
})
);
assert_eq!(
Date::ymd(2026, 1, 32),
Err(ValidationError::InvalidDate {
rule: "day-out-of-range",
})
);
assert_eq!(
Date::ymd(2026, 4, 31),
Err(ValidationError::InvalidDate {
rule: "day-out-of-range",
})
);
}
#[test]
fn ymd_rejects_feb_29_in_non_leap() {
assert_eq!(
Date::ymd(2025, 2, 29),
Err(ValidationError::InvalidDate {
rule: "day-out-of-range",
})
);
assert!(Date::ymd(2024, 2, 29).is_ok());
}
#[test]
fn day_of_week_named_dates() {
assert_eq!(
Date::ymd(1900, 1, 1).unwrap().day_of_week(),
Weekday::Mon,
"1900-01-01"
);
assert_eq!(
Date::ymd(1999, 12, 31).unwrap().day_of_week(),
Weekday::Fri,
"1999-12-31"
);
assert_eq!(
Date::ymd(2000, 1, 1).unwrap().day_of_week(),
Weekday::Sat,
"2000-01-01"
);
assert_eq!(
Date::ymd(2020, 2, 29).unwrap().day_of_week(),
Weekday::Sat,
"2020-02-29"
);
assert_eq!(
Date::ymd(2024, 12, 25).unwrap().day_of_week(),
Weekday::Wed,
"2024-12-25"
);
assert_eq!(
Date::ymd(2026, 1, 1).unwrap().day_of_week(),
Weekday::Thu,
"2026-01-01"
);
assert_eq!(
Date::ymd(2026, 5, 23).unwrap().day_of_week(),
Weekday::Sat,
"2026-05-23"
);
assert_eq!(
Date::ymd(2026, 12, 31).unwrap().day_of_week(),
Weekday::Thu,
"2026-12-31"
);
assert_eq!(
Date::ymd(2038, 1, 19).unwrap().day_of_week(),
Weekday::Tue,
"2038-01-19"
);
assert_eq!(
Date::ymd(1969, 7, 20).unwrap().day_of_week(),
Weekday::Sun,
"1969-07-20 (Apollo 11 Moon landing)"
);
}
#[test]
fn day_of_week_cycles_correctly() {
let mut d = Date::ymd(2026, 1, 5).unwrap(); let expected = [
Weekday::Mon,
Weekday::Tue,
Weekday::Wed,
Weekday::Thu,
Weekday::Fri,
Weekday::Sat,
Weekday::Sun,
];
for &e in &expected {
assert_eq!(d.day_of_week(), e);
d = d.add_days(1);
}
}
#[test]
fn add_days_into_next_month() {
assert_eq!(
Date::ymd(2026, 1, 1).unwrap().add_days(31),
Date::ymd(2026, 2, 1).unwrap()
);
}
#[test]
fn add_days_leap_boundary() {
assert_eq!(
Date::ymd(2024, 2, 28).unwrap().add_days(1),
Date::ymd(2024, 2, 29).unwrap()
);
assert_eq!(
Date::ymd(2025, 2, 28).unwrap().add_days(1),
Date::ymd(2025, 3, 1).unwrap()
);
}
#[test]
fn add_days_year_boundary() {
assert_eq!(
Date::ymd(2026, 12, 31).unwrap().add_days(1),
Date::ymd(2027, 1, 1).unwrap()
);
}
#[test]
fn add_days_round_trip_small_grid() {
let anchor = Date::ymd(2026, 5, 23).unwrap();
for &n in &[
-10_000, -3_653, -366, -365, -100, -7, -1, 0, 1, 7, 100, 365, 366, 3_653, 10_000,
] {
assert_eq!(anchor.add_days(n).add_days(-n), anchor, "offset {n}");
}
}
#[test]
fn add_days_round_trip_proptest() {
use proptest::prelude::*;
let anchor = Date::ymd(2026, 5, 23).unwrap();
proptest!(|(n in -10_000i32..10_000)| {
prop_assert_eq!(anchor.add_days(n).add_days(-n), anchor);
});
}
#[test]
fn add_months_eom_aware_non_leap_clamp() {
assert_eq!(
Date::ymd(2026, 1, 31).unwrap().add_months_eom_aware(1),
Date::ymd(2026, 2, 28).unwrap()
);
}
#[test]
fn add_months_eom_aware_leap_keeps_29() {
assert_eq!(
Date::ymd(2024, 1, 31).unwrap().add_months_eom_aware(1),
Date::ymd(2024, 2, 29).unwrap()
);
}
#[test]
fn add_months_eom_aware_year_rollover() {
assert_eq!(
Date::ymd(2026, 12, 31).unwrap().add_months_eom_aware(1),
Date::ymd(2027, 1, 31).unwrap()
);
}
#[test]
fn add_months_eom_aware_negative_rollover() {
assert_eq!(
Date::ymd(2026, 3, 31).unwrap().add_months_eom_aware(-1),
Date::ymd(2026, 2, 28).unwrap()
);
assert_eq!(
Date::ymd(2024, 3, 31).unwrap().add_months_eom_aware(-1),
Date::ymd(2024, 2, 29).unwrap()
);
assert_eq!(
Date::ymd(2026, 5, 15).unwrap().add_months_eom_aware(-12),
Date::ymd(2025, 5, 15).unwrap()
);
}
#[test]
fn nth_weekday_third_friday_june_2026() {
assert_eq!(
Date::nth_weekday_of_month(2026, 6, 3, Weekday::Fri).unwrap(),
Date::ymd(2026, 6, 19).unwrap()
);
}
#[test]
fn nth_weekday_fifth_monday_feb_2026_does_not_exist() {
assert_eq!(
Date::nth_weekday_of_month(2026, 2, 5, Weekday::Mon),
Err(ValidationError::OutOfRange {
what: "nth weekday does not exist in this month",
})
);
}
#[test]
fn nth_weekday_first_of_each_weekday_jan_2026() {
let cases = [
(Weekday::Thu, 1),
(Weekday::Fri, 2),
(Weekday::Sat, 3),
(Weekday::Sun, 4),
(Weekday::Mon, 5),
(Weekday::Tue, 6),
(Weekday::Wed, 7),
];
for (wd, day) in cases {
assert_eq!(
Date::nth_weekday_of_month(2026, 1, 1, wd).unwrap(),
Date::ymd(2026, 1, day).unwrap(),
"first {wd:?} of Jan 2026",
);
}
}
#[test]
fn nth_weekday_rejects_invalid_n_and_month() {
assert_eq!(
Date::nth_weekday_of_month(2026, 1, 0, Weekday::Mon),
Err(ValidationError::OutOfRange {
what: "n must be 1..=5",
})
);
assert_eq!(
Date::nth_weekday_of_month(2026, 13, 1, Weekday::Mon),
Err(ValidationError::InvalidDate {
rule: "month-out-of-range",
})
);
}
#[test]
fn easter_sunday_known_dates() {
let cases = [
(2024, 3, 31),
(2025, 4, 20),
(2026, 4, 5),
(2027, 3, 28),
(2028, 4, 16),
(2030, 4, 21),
(2038, 4, 25),
];
for (y, m, d) in cases {
assert_eq!(
Date::easter_sunday(y),
Date::ymd(y, m, d).unwrap(),
"Easter {y}",
);
}
}
#[test]
fn days_between_one_day() {
let a = Date::ymd(2026, 1, 1).unwrap();
let b = Date::ymd(2026, 1, 2).unwrap();
assert_eq!(a.days_between(b), 1);
assert_eq!(b.days_between(a), -1);
}
#[test]
fn days_between_same_date_is_zero() {
let a = Date::ymd(2026, 5, 23).unwrap();
assert_eq!(a.days_between(a), 0);
}
#[test]
fn days_between_year_is_365_or_366() {
let s = Date::ymd(2025, 1, 1).unwrap();
let e = Date::ymd(2026, 1, 1).unwrap();
assert_eq!(s.days_between(e), 365);
let s = Date::ymd(2024, 1, 1).unwrap();
let e = Date::ymd(2025, 1, 1).unwrap();
assert_eq!(s.days_between(e), 366);
}
#[test]
fn days_between_additive() {
let a = Date::ymd(2024, 1, 1).unwrap();
let b = Date::ymd(2024, 7, 15).unwrap();
let c = Date::ymd(2025, 3, 31).unwrap();
assert_eq!(
a.days_between(b) + b.days_between(c),
a.days_between(c),
"additivity",
);
}
#[test]
fn days_between_additive_proptest() {
use proptest::prelude::*;
let anchor = Date::ymd(2026, 1, 1).unwrap();
proptest!(|(n1 in -3_000i32..3_000, n2 in -3_000i32..3_000)| {
let b = anchor.add_days(n1);
let c = b.add_days(n2);
prop_assert_eq!(
anchor.days_between(b) + b.days_between(c),
anchor.days_between(c),
);
});
}
#[test]
fn date_ordering_is_chronological() {
let a = Date::ymd(2026, 1, 1).unwrap();
let b = Date::ymd(2026, 1, 2).unwrap();
let c = Date::ymd(2026, 2, 1).unwrap();
let d = Date::ymd(2027, 1, 1).unwrap();
assert!(a < b);
assert!(b < c);
assert!(c < d);
}
#[test]
fn date_is_copy() {
let a = Date::ymd(2026, 5, 23).unwrap();
let b = a; assert_eq!(a, b);
}
}