use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct CivilDate {
year: i64,
month: u32,
day: u32,
}
pub(crate) const MONTH_NAMES: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
pub(crate) const MONTH_SHORT_NAMES: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
pub(crate) const WEEKDAY_SHORT_NAMES: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
pub(crate) const WEEKDAY_NAMES: [&str; 7] = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
fn is_leap_year(year: i64) -> bool {
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
pub(crate) fn days_in_month(year: i64, month: u32) -> u32 {
match month {
2 if is_leap_year(year) => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
fn read_digits(bytes: &[u8], start: usize, count: usize) -> Option<u32> {
let digits = bytes.get(start..start + count)?;
let mut value = 0_u32;
for digit in digits {
if !digit.is_ascii_digit() {
return None;
}
value = value * 10 + u32::from(digit - b'0');
}
Some(value)
}
impl CivilDate {
pub(crate) fn new(year: i64, month: u32, day: u32) -> Option<Self> {
if !(1..=12).contains(&month) || day == 0 || day > days_in_month(year, month) {
return None;
}
Some(Self { year, month, day })
}
pub(crate) fn parse(value: &str) -> Option<Self> {
let bytes = value.as_bytes();
if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
return None;
}
let year = read_digits(bytes, 0, 4)?;
let month = read_digits(bytes, 5, 2)?;
let day = read_digits(bytes, 8, 2)?;
if year == 0 {
return None;
}
Self::new(i64::from(year), month, day)
}
pub(crate) fn parse_month(value: &str) -> Option<Self> {
let bytes = value.as_bytes();
if bytes.len() != 7 || bytes[4] != b'-' {
return None;
}
let year = read_digits(bytes, 0, 4)?;
let month = read_digits(bytes, 5, 2)?;
if year == 0 {
return None;
}
Self::new(i64::from(year), month, 1)
}
pub(crate) fn year(self) -> i64 {
self.year
}
pub(crate) fn month(self) -> u32 {
self.month
}
pub(crate) fn day(self) -> u32 {
self.day
}
fn to_days(self) -> i64 {
let year = if self.month <= 2 {
self.year - 1
} else {
self.year
};
let era = year.div_euclid(400);
let year_of_era = year - era * 400;
let month = i64::from(self.month);
let day_of_year =
(153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + i64::from(self.day) - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}
fn from_days(days: i64) -> Self {
let shifted = days + 719_468;
let era = shifted.div_euclid(146_097);
let day_of_era = shifted - era * 146_097;
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_index = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
let month = if month_index < 10 {
month_index + 3
} else {
month_index - 9
};
let year = year_of_era + era * 400 + i64::from(month <= 2);
Self {
year,
month: u32::try_from(month).unwrap_or(1),
day: u32::try_from(day).unwrap_or(1),
}
}
pub(crate) fn from_unix_seconds(seconds: i64) -> Self {
Self::from_days(seconds.div_euclid(86_400))
}
pub(crate) fn add_days(self, days: i64) -> Self {
Self::from_days(self.to_days() + days)
}
pub(crate) fn add_months(self, months: i64) -> Self {
let index = self.year * 12 + i64::from(self.month) - 1 + months;
let year = index.div_euclid(12);
let month = u32::try_from(index.rem_euclid(12)).unwrap_or(0) + 1;
let day = self.day.min(days_in_month(year, month));
Self { year, month, day }
}
pub(crate) fn start_of_month(self) -> Self {
Self { day: 1, ..self }
}
pub(crate) fn days_in_month(self) -> u32 {
days_in_month(self.year, self.month)
}
pub(crate) fn weekday_index(self) -> usize {
usize::try_from((self.to_days() + 3).rem_euclid(7)).unwrap_or(0)
}
pub(crate) fn same_month(self, other: Self) -> bool {
self.year == other.year && self.month == other.month
}
pub(crate) fn month_key(self) -> String {
let iso = self.to_string();
iso[..iso.len() - 3].to_string()
}
pub(crate) fn grid_start(self) -> Self {
let first = self.start_of_month();
first.add_days(-i64::try_from(first.weekday_index()).unwrap_or(0))
}
pub(crate) fn clamp_to(self, min: Option<Self>, max: Option<Self>) -> Self {
if let Some(min) = min
&& self < min
{
return min;
}
if let Some(max) = max
&& self > max
{
return max;
}
self
}
}
impl fmt::Display for CivilDate {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if (0..=9999).contains(&self.year) {
write!(
formatter,
"{:04}-{:02}-{:02}",
self.year, self.month, self.day
)
} else if self.year > 9999 {
write!(
formatter,
"+{:06}-{:02}-{:02}",
self.year, self.month, self.day
)
} else {
write!(
formatter,
"-{:06}-{:02}-{:02}",
self.year.unsigned_abs(),
self.month,
self.day
)
}
}
}
pub(crate) fn bounds_valid(min: Option<&str>, max: Option<&str>) -> bool {
let min_date = min.map(CivilDate::parse);
let max_date = max.map(CivilDate::parse);
if matches!(min_date, Some(None)) || matches!(max_date, Some(None)) {
return false;
}
match (min, max) {
(Some(min), Some(max)) if !min.is_empty() && !max.is_empty() => min <= max,
_ => true,
}
}
pub(crate) fn utc_today() -> Option<CivilDate> {
#[cfg(not(target_family = "wasm"))]
{
let seconds = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()?
.as_secs();
Some(CivilDate::from_unix_seconds(i64::try_from(seconds).ok()?))
}
#[cfg(target_family = "wasm")]
{
None
}
}
#[cfg(test)]
mod tests {
use super::{CivilDate, bounds_valid};
fn date(value: &str) -> CivilDate {
CivilDate::parse(value).expect("valid test date")
}
#[test]
fn parses_only_complete_real_dates() {
assert_eq!(date("2024-02-29").to_string(), "2024-02-29");
assert!(CivilDate::parse("2023-02-29").is_none());
assert!(CivilDate::parse("2024-13-01").is_none());
assert!(CivilDate::parse("2024-00-10").is_none());
assert!(CivilDate::parse("0000-01-01").is_none());
assert!(CivilDate::parse("2024-1-01").is_none());
assert!(CivilDate::parse("2024-01-01").is_none());
assert!(CivilDate::parse("2024-01-01T").is_none());
assert!(CivilDate::parse(&"9".repeat(100_000)).is_none());
assert_eq!(
CivilDate::parse_month("2024-03").map(|value| value.to_string()),
Some("2024-03-01".to_string())
);
assert!(CivilDate::parse_month("2024-3").is_none());
}
#[test]
fn date_math_matches_the_utc_calendar() {
assert_eq!(date("2024-03-01").add_days(-1).to_string(), "2024-02-29");
assert_eq!(date("2023-12-31").add_days(1).to_string(), "2024-01-01");
assert_eq!(date("2024-01-31").add_months(1).to_string(), "2024-02-29");
assert_eq!(date("2024-03-31").add_months(-1).to_string(), "2024-02-29");
assert_eq!(date("2024-01-15").add_months(-13).to_string(), "2022-12-15");
assert_eq!(date("9999-12-31").add_days(1).to_string(), "+010000-01-01");
assert_eq!(date("2024-03-01").month_key(), "2024-03");
assert_eq!(CivilDate::from_unix_seconds(0).to_string(), "1970-01-01");
assert_eq!(
CivilDate::from_unix_seconds(1_709_251_200).to_string(),
"2024-03-01"
);
}
#[test]
fn weeks_start_on_monday() {
assert_eq!(date("2026-01-05").weekday_index(), 0);
assert_eq!(date("2024-03-01").weekday_index(), 4);
assert_eq!(date("2024-03-17").grid_start().to_string(), "2024-02-26");
assert_eq!(date("2024-04-10").grid_start().to_string(), "2024-04-01");
}
#[test]
fn clamps_and_validates_bounds() {
let min = Some(date("2024-03-05"));
let max = Some(date("2024-03-20"));
assert_eq!(
date("2024-03-01").clamp_to(min, max).to_string(),
"2024-03-05"
);
assert_eq!(
date("2024-03-25").clamp_to(min, max).to_string(),
"2024-03-20"
);
assert!(bounds_valid(Some("2024-01-01"), Some("2024-12-31")));
assert!(!bounds_valid(Some("2024-12-31"), Some("2024-01-01")));
assert!(!bounds_valid(Some("nope"), None));
assert!(bounds_valid(None, None));
}
}