use std::fmt;
use std::ops::{Add, Sub};
use thiserror::Error;
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum DateError {
#[error("Year {0} is out of valid range [-9999, 9999]")]
InvalidYear(i32),
#[error("Month {0} is invalid (must be 1..=12)")]
InvalidMonth(u8),
#[error("Day {day} is invalid for month {month} in year {year}")]
InvalidDay {
day: u8,
month: u8,
year: i32,
},
#[error("Date calculation resulted in overflow")]
Overflow,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Month {
January = 1,
February = 2,
March = 3,
April = 4,
May = 5,
June = 6,
July = 7,
August = 8,
September = 9,
October = 10,
November = 11,
December = 12,
}
impl Month {
pub fn from_number(n: u8) -> Result<Self, DateError> {
match n {
1 => Ok(Self::January),
2 => Ok(Self::February),
3 => Ok(Self::March),
4 => Ok(Self::April),
5 => Ok(Self::May),
6 => Ok(Self::June),
7 => Ok(Self::July),
8 => Ok(Self::August),
9 => Ok(Self::September),
10 => Ok(Self::October),
11 => Ok(Self::November),
12 => Ok(Self::December),
_ => Err(DateError::InvalidMonth(n)),
}
}
#[inline]
pub fn as_number(self) -> u8 {
self as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Weekday {
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}
impl Weekday {
#[inline]
pub fn is_weekend(self) -> bool {
matches!(self, Self::Saturday | Self::Sunday)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Period {
Days(i64),
Weeks(i64),
Months(i64),
Years(i64),
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Date {
serial: i64,
}
impl Date {
pub fn from_ymd(year: i32, month: Month, day: u8) -> Result<Self, DateError> {
if !(-9999..=9999).contains(&year) {
return Err(DateError::InvalidYear(year));
}
let m = month.as_number();
let max_days = days_in_month(year, month);
if day < 1 || day > max_days {
return Err(DateError::InvalidDay {
day,
month: m,
year,
});
}
let serial = days_from_civil(year, m, day);
Ok(Self { serial })
}
#[inline]
pub const fn from_serial(serial: i64) -> Self {
Self { serial }
}
#[inline]
pub const fn serial(&self) -> i64 {
self.serial
}
#[inline]
pub fn year(&self) -> i32 {
let (y, _, _) = civil_from_days(self.serial);
y
}
#[inline]
pub fn month(&self) -> Month {
let (_, m, _) = civil_from_days(self.serial);
Month::from_number(m).expect("civil_from_days returns valid month")
}
#[inline]
pub fn day(&self) -> u8 {
let (_, _, d) = civil_from_days(self.serial);
d
}
#[inline]
pub fn ymd(&self) -> (i32, Month, u8) {
let (y, m, d) = civil_from_days(self.serial);
(
y,
Month::from_number(m).expect("valid month from civil_from_days"),
d,
)
}
#[inline]
pub fn weekday(&self) -> Weekday {
let wd = ((self.serial + 3).rem_euclid(7)) + 1;
match wd {
1 => Weekday::Monday,
2 => Weekday::Tuesday,
3 => Weekday::Wednesday,
4 => Weekday::Thursday,
5 => Weekday::Friday,
6 => Weekday::Saturday,
7 => Weekday::Sunday,
_ => unreachable!(),
}
}
#[inline]
pub fn is_leap_year(&self) -> bool {
is_leap_year(self.year())
}
#[inline]
pub fn is_end_of_month(&self) -> bool {
let (y, m, d) = self.ymd();
d == days_in_month(y, m)
}
pub fn day_of_year(&self) -> u16 {
let (y, _, _) = self.ymd();
let jan1 = days_from_civil(y, 1, 1);
(self.serial - jan1 + 1) as u16
}
pub fn end_of_month(year: i32, month: Month) -> Result<Self, DateError> {
let max_day = days_in_month(year, month);
Self::from_ymd(year, month, max_day)
}
pub fn advance(&self, period: Period, preserve_end_of_month: bool) -> Result<Self, DateError> {
match period {
Period::Days(n) => self
.serial
.checked_add(n)
.map(Self::from_serial)
.ok_or(DateError::Overflow),
Period::Weeks(w) => {
let days = w.checked_mul(7).ok_or(DateError::Overflow)?;
self.advance(Period::Days(days), preserve_end_of_month)
}
Period::Months(m) => {
let (y, current_month, d) = self.ymd();
let is_eom = preserve_end_of_month && self.is_end_of_month();
let total_months = (y as i64) * 12 + (current_month.as_number() as i64 - 1) + m;
let target_year = (total_months.div_euclid(12)) as i32;
let target_month_num = (total_months.rem_euclid(12) + 1) as u8;
let target_month = Month::from_number(target_month_num)?;
let target_max_days = days_in_month(target_year, target_month);
let target_day = if is_eom {
target_max_days
} else {
d.min(target_max_days)
};
Self::from_ymd(target_year, target_month, target_day)
}
Period::Years(y) => {
let months = y.checked_mul(12).ok_or(DateError::Overflow)?;
self.advance(Period::Months(months), preserve_end_of_month)
}
}
}
}
#[inline]
fn days_from_civil(year: i32, month: u8, day: u8) -> i64 {
let y = year - i32::from(month <= 2);
let era = (if y >= 0 { y } else { y - 399 }) / 400;
let yoe = (y - era * 400) as u32;
let m = month as u32;
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as u32 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era as i64 * 146_097 + doe as i64 - 719_468
}
#[inline]
fn civil_from_days(z: i64) -> (i32, u8, u8) {
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 / 36524 - doe / 146_096) / 365;
let y = yoe as i32 + era as i32 * 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 y = y + i32::from(m <= 2);
(y, m, d)
}
#[inline]
pub const fn is_leap_year(year: i32) -> bool {
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}
#[inline]
pub fn days_in_month(year: i32, month: Month) -> u8 {
match month {
Month::January
| Month::March
| Month::May
| Month::July
| Month::August
| Month::October
| Month::December => 31,
Month::April | Month::June | Month::September | Month::November => 30,
Month::February => {
if is_leap_year(year) {
29
} else {
28
}
}
}
}
impl Add<i64> for Date {
type Output = Self;
#[inline]
fn add(self, days: i64) -> Self::Output {
Self::from_serial(self.serial + days)
}
}
impl Sub<i64> for Date {
type Output = Self;
#[inline]
fn sub(self, days: i64) -> Self::Output {
Self::from_serial(self.serial - days)
}
}
impl Sub<Date> for Date {
type Output = i64;
#[inline]
fn sub(self, rhs: Date) -> Self::Output {
self.serial - rhs.serial
}
}
impl fmt::Display for Date {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (y, m, d) = self.ymd();
write!(f, "{:04}-{:02}-{:02}", y, m.as_number(), d)
}
}
impl fmt::Debug for Date {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Date({})", self)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_date_civil_roundtrip() {
for year in [1900, 1901, 1999, 2000, 2004, 2024, 2026, 2100] {
for month_idx in 1..=12 {
let month = Month::from_number(month_idx).unwrap();
let max_d = days_in_month(year, month);
for day in [1, 15, max_d] {
let d = Date::from_ymd(year, month, day).unwrap();
assert_eq!(d.year(), year);
assert_eq!(d.month(), month);
assert_eq!(d.day(), day);
}
}
}
}
#[test]
fn test_leap_years() {
assert!(!is_leap_year(1900)); assert!(is_leap_year(2000)); assert!(is_leap_year(2024)); assert!(!is_leap_year(2023));
assert!(!is_leap_year(2100));
}
#[test]
fn test_weekday() {
let epoch = Date::from_ymd(1970, Month::January, 1).unwrap();
assert_eq!(epoch.weekday(), Weekday::Thursday);
let d = Date::from_ymd(2026, Month::September, 3).unwrap();
assert_eq!(d.weekday(), Weekday::Thursday);
let leap_d = Date::from_ymd(2024, Month::February, 29).unwrap();
assert_eq!(leap_d.weekday(), Weekday::Thursday);
}
#[test]
fn test_advance_months_end_of_month() {
let jan31 = Date::from_ymd(2024, Month::January, 31).unwrap();
let feb29 = jan31.advance(Period::Months(1), false).unwrap();
assert_eq!(feb29, Date::from_ymd(2024, Month::February, 29).unwrap());
let jan31_2023 = Date::from_ymd(2023, Month::January, 31).unwrap();
let feb28_2023 = jan31_2023.advance(Period::Months(1), false).unwrap();
assert_eq!(
feb28_2023,
Date::from_ymd(2023, Month::February, 28).unwrap()
);
}
#[test]
fn test_day_difference() {
let d1 = Date::from_ymd(2026, Month::January, 1).unwrap();
let d2 = Date::from_ymd(2026, Month::January, 11).unwrap();
assert_eq!(d2 - d1, 10);
assert_eq!(d1 - d2, -10);
}
}