use std::fmt::Write as _;
use crate::params::{
DAYS_PER_WEEK, FULL_NAME_LETTERS, HOURS_PER_DAY, HOURS_PER_HALF_DAY, LEAP_YEAR_CYCLES, MARCH,
MAX_DAY_OF_MONTH, MAX_SECONDS_PER_MINUTE, MINUTES_PER_HOUR, MONTH_DAYS, MONTHS_PER_YEAR,
SHORT_NAME_LETTERS, WEEKDAY_SHIFTS, YEAR_DIGITS, YEARS_PER_CENTURY,
};
const AM_PM: &str = "AM/PM";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DateTime {
pub year: i32,
pub month: u8,
pub day: u8,
pub hour: u8,
pub minute: u8,
pub second: u8,
}
const MONTHS: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const DAYS: [&str; 7] = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
fn month_of(word: &str) -> Option<u8> {
let word = word.trim_end_matches(['.', ',']).to_lowercase();
let index = MONTHS.iter().position(|name| {
let name = name.to_lowercase();
word == name || (word.len() == SHORT_NAME_LETTERS && name.starts_with(&word))
})?;
u8::try_from(index + 1).ok()
}
fn days_in_month(year: i32, month: u8) -> u8 {
let (leap, century, cycle) = LEAP_YEAR_CYCLES;
let is_leap = year.rem_euclid(leap) == 0
&& (year.rem_euclid(century) != 0 || year.rem_euclid(cycle) == 0);
let days = usize::from(month)
.checked_sub(1)
.and_then(|index| MONTH_DAYS.get(index).copied())
.unwrap_or(MAX_DAY_OF_MONTH);
let leap_day = usize::from(month) + 1 == MARCH && is_leap;
days + u8::from(leap_day)
}
fn day_of(word: &str) -> Option<u8> {
word.trim_end_matches(',').parse().ok()
}
fn iso_date(text: &str) -> Option<(i32, u8, u8)> {
let mut parts = text.split('T').next()?.split('-');
let year = parts.next()?.parse().ok()?;
Some((
year,
parts.next()?.parse().ok()?,
parts.next()?.parse().ok()?,
))
}
pub const DATE_PICTURE: &str = "M/d/yyyy";
pub const TIME_PICTURE: &str = "h:mm AM/PM";
pub const SAVED_DATE_PICTURE: &str = "M/d/yyyy h:mm:'00' AM/PM";
pub const PROPERTY_DATE_PICTURE: &str = "d/M/yyyy";
impl DateTime {
#[must_use]
pub fn local_date(self, zone_minutes: i32) -> Self {
let per_hour = i32::from(MINUTES_PER_HOUR);
let minutes = i32::from(self.hour) * per_hour + i32::from(self.minute);
let days = (minutes + zone_minutes).div_euclid(i32::from(HOURS_PER_DAY) * per_hour);
let mut date = Self {
hour: 0,
minute: 0,
second: 0,
..self
};
for _ in 0..days.unsigned_abs() {
date = if days > 0 {
date.next_day()
} else {
date.day_before()
};
}
date
}
fn next_day(self) -> Self {
if self.day < days_in_month(self.year, self.month) {
Self {
day: self.day + 1,
..self
}
} else if self.month < MONTHS_PER_YEAR {
Self {
month: self.month + 1,
day: 1,
..self
}
} else {
Self {
year: self.year.saturating_add(1),
month: 1,
day: 1,
..self
}
}
}
fn day_before(self) -> Self {
if self.day > 1 {
Self {
day: self.day - 1,
..self
}
} else if self.month > 1 {
let month = self.month - 1;
Self {
month,
day: days_in_month(self.year, month),
..self
}
} else {
let year = self.year.saturating_sub(1);
Self {
year,
month: MONTHS_PER_YEAR,
day: days_in_month(year, MONTHS_PER_YEAR),
..self
}
}
}
#[must_use]
pub fn parse_utc(text: &str) -> Option<Self> {
let text = text.trim().strip_suffix('Z')?;
let (date, time) = text.split_once('T')?;
let mut date = date.split('-');
let mut time = time.split(':');
let next = |part: Option<&str>| part.and_then(|p| p.split('.').next()?.parse().ok());
let year: i32 = date.next()?.parse().ok()?;
let parsed = Self {
year,
month: next(date.next())?,
day: next(date.next())?,
hour: next(time.next())?,
minute: next(time.next())?,
second: next(time.next()).unwrap_or(0),
};
let valid = (1..=MONTHS_PER_YEAR).contains(&parsed.month)
&& (1..=MAX_DAY_OF_MONTH).contains(&parsed.day)
&& parsed.hour < HOURS_PER_DAY
&& parsed.minute < MINUTES_PER_HOUR
&& parsed.second < MAX_SECONDS_PER_MINUTE;
valid.then_some(parsed)
}
#[must_use]
pub fn parse_text(text: &str) -> Option<Self> {
let words: Vec<&str> = text.split_whitespace().collect();
let (year, month, day) = match words.as_slice() {
[d, m, y] if day_of(d).is_some() => (y.parse().ok()?, month_of(m)?, day_of(d)?),
[m, d, y] => (y.parse().ok()?, month_of(m)?, day_of(d)?),
[iso] => iso_date(iso)?,
_ => return None,
};
let valid = (1..=MONTHS_PER_YEAR).contains(&month) && (1..=MAX_DAY_OF_MONTH).contains(&day);
valid.then_some(Self {
year,
month,
day,
hour: 0,
minute: 0,
second: 0,
})
}
fn weekday(self) -> usize {
let month = usize::from(self.month.clamp(1, MONTHS_PER_YEAR));
let year = i64::from(self.year) - i64::from(month < MARCH);
let shift = i64::from(WEEKDAY_SHIFTS.get(month - 1).copied().unwrap_or(0));
let (leap, century, cycle) = LEAP_YEAR_CYCLES;
let years = |cycle: i32| year.div_euclid(i64::from(cycle));
let day = year + years(leap) - years(century) + years(cycle) + shift + i64::from(self.day);
usize::try_from(day.rem_euclid(i64::from(DAYS_PER_WEEK))).unwrap_or(0)
}
#[must_use]
pub fn write(self, picture: &str) -> String {
let chars: Vec<char> = picture.chars().collect();
let mut out = String::new();
let mut i = 0;
while let Some(&ch) = chars.get(i) {
let rest = chars.get(i..).unwrap_or_default();
let run = rest.iter().take_while(|&&c| c == ch).count();
let starts = |text: &str, lower: bool| {
let text = text
.chars()
.map(|c| if lower { c.to_ascii_lowercase() } else { c });
rest.iter().copied().take(AM_PM.len()).eq(text)
};
if ch == '\'' {
let end = chars
.get(i + 1..)
.and_then(|tail| tail.iter().position(|&c| c == '\''))
.map_or(chars.len(), |p| i + 1 + p);
out.extend(chars.get(i + 1..end).unwrap_or_default());
i = end + 1;
continue;
}
if starts(AM_PM, false) || starts(AM_PM, true) {
let pm = self.hour >= HOURS_PER_HALF_DAY;
let text = match (pm, ch == 'A') {
(true, true) => "PM",
(false, true) => "AM",
(true, false) => "pm",
(false, false) => "am",
};
out.push_str(text);
i += AM_PM.len();
continue;
}
let wrote = self.field(ch, run, &mut out);
if wrote {
i += run;
} else {
let kept = run.saturating_sub(1).max(1);
out.extend(std::iter::repeat_n(ch, kept));
i += kept;
}
}
out
}
fn field(self, ch: char, count: usize, out: &mut String) -> bool {
let number = |out: &mut String, value: u32, width: usize| {
let _ = write!(out, "{value:0width$}");
};
let name = |names: &[&str], index: usize, count: usize| {
let full = names.get(index).copied().unwrap_or("");
if count == SHORT_NAME_LETTERS {
full.chars().take(SHORT_NAME_LETTERS).collect()
} else {
full.to_owned()
}
};
let hour12 = match self.hour % HOURS_PER_HALF_DAY {
0 => HOURS_PER_HALF_DAY,
h => h,
};
match (ch, count) {
('d', 1 | 2) => number(out, u32::from(self.day), count),
('d', _) => out.push_str(&name(&DAYS, self.weekday(), count.min(FULL_NAME_LETTERS))),
('M', 1 | 2) => number(out, u32::from(self.month), count),
('M', _) => {
let index = usize::from(self.month.clamp(1, MONTHS_PER_YEAR)) - 1;
out.push_str(&name(&MONTHS, index, count.min(FULL_NAME_LETTERS)));
}
('y', 1 | 2) => number(
out,
self.year.rem_euclid(YEARS_PER_CENTURY).unsigned_abs(),
2,
),
('y', _) => number(out, self.year.unsigned_abs(), YEAR_DIGITS),
('h', _) => number(out, u32::from(hour12), count.min(2)),
('H', _) => number(out, u32::from(self.hour), count.min(2)),
('m', _) => number(out, u32::from(self.minute), count.min(2)),
('s', _) => number(out, u32::from(self.second), count.min(2)),
_ => return false,
}
true
}
}
#[cfg(test)]
mod tests {
use super::DateTime;
fn date(year: i32, month: u8, day: u8, hour: u8) -> DateTime {
DateTime {
year,
month,
day,
hour,
minute: 0,
second: 0,
}
}
#[test]
fn reads_times_of_date_properties() {
let utc = DateTime::parse_utc("2018-12-28T13:00:00Z");
assert_eq!(utc, Some(date(2018, 12, 28, 13)));
assert_eq!(DateTime::parse_utc("2018-12-28"), None);
assert_eq!(DateTime::parse_utc("2018-13-28T13:00:00Z"), None);
}
#[test]
fn takes_the_date_of_a_utc_time_in_a_zone_at_midnight() {
let at = |year, month, day, hour, minute| DateTime {
year,
month,
day,
hour,
minute,
second: 30,
};
let day = |year, month, day| date(year, month, day, 0);
let cases = [
(at(2026, 1, 15, 3, 30), 480, day(2026, 1, 15)),
(at(2026, 7, 15, 3, 30), 480, day(2026, 7, 15)),
(at(2026, 1, 15, 23, 30), 480, day(2026, 1, 16)),
(at(2026, 12, 31, 20, 0), 480, day(2027, 1, 1)),
(at(2024, 2, 28, 16, 0), 480, day(2024, 2, 29)),
(at(2023, 2, 28, 16, 0), 480, day(2023, 3, 1)),
(at(1900, 2, 28, 16, 0), 480, day(1900, 3, 1)),
(at(2000, 2, 28, 16, 0), 480, day(2000, 2, 29)),
(at(2026, 4, 30, 15, 59), 480, day(2026, 4, 30)),
(at(2026, 3, 1, 2, 0), -300, day(2026, 2, 28)),
(at(2024, 3, 1, 2, 0), -300, day(2024, 2, 29)),
(at(2026, 1, 1, 1, 0), -300, day(2025, 12, 31)),
(at(2026, 5, 1, 4, 59), -300, day(2026, 4, 30)),
(at(2026, 5, 1, 5, 0), -300, day(2026, 5, 1)),
(at(2026, 1, 15, 23, 59), 0, day(2026, 1, 15)),
];
for (utc, zone, local) in cases {
assert_eq!(utc.local_date(zone), local, "{utc:?} {zone}");
}
assert_eq!(
day(2026, 1, 15)
.local_date(480)
.write(super::PROPERTY_DATE_PICTURE),
"15/1/2026"
);
}
#[test]
fn reads_dates_written_as_text() {
for text in [
"20 April 2023",
"20 Apr 2023",
"April 20, 2023",
"2023-04-20",
] {
assert_eq!(
DateTime::parse_text(text),
Some(date(2023, 4, 20, 0)),
"{text}"
);
}
for text in ["Unknown", "20 Avril 2023", "32 April 2023", "April"] {
assert_eq!(DateTime::parse_text(text), None, "{text}");
}
assert_eq!(date(2023, 4, 20, 0).write("dd/MM/yyyy"), "20/04/2023");
}
const PRINTED: DateTime = DateTime {
year: 2026,
month: 9,
day: 25,
hour: 14,
minute: 33,
second: 2,
};
#[test]
fn writes_dates_and_times_with_pictures() {
let cases = [
("dddd, MMMM d, yyyy", "Friday, September 25, 2026"),
("d MMMM yyyy", "25 September 2026"),
("yyyy", "2026"),
("M/d/yyyy", "9/25/2026"),
("dd/MM/yy", "25/09/26"),
("ddd d MMM", "Fri 25 Sep"),
("dd/MM/yyyy H:mm:ss", "25/09/2026 14:33:02"),
("d/M/yyyy h:mm AM/PM", "25/9/2026 2:33 PM"),
("h:mm am/pm", "2:33 pm"),
("'Week of' d MMMM", "Week of 25 September"),
("d.M.yyyy", "25.9.2026"),
("xxAAAM/PM zz", "xxAAPM zz"),
("aaam/pm aAM/PM", "aapm aPM"),
("AAM/P", "AA9/P"),
(super::SAVED_DATE_PICTURE, "9/25/2026 2:33:00 PM"),
];
for (picture, text) in cases {
assert_eq!(PRINTED.write(picture), text, "{picture}");
}
}
#[test]
fn finds_the_day_of_the_week() {
let day = |year, month, day| DateTime {
year,
month,
day,
hour: 0,
minute: 0,
second: 0,
};
assert_eq!(day(2026, 9, 25).write("dddd"), "Friday");
assert_eq!(day(2000, 1, 1).write("dddd"), "Saturday");
assert_eq!(day(2024, 2, 29).write("dddd"), "Thursday");
assert_eq!(day(2026, 11, 5).write("dddd"), "Thursday");
}
#[test]
fn finds_the_day_of_the_week_at_the_ends_of_32_bits_and_before_the_year_1() {
let day = |year, month, day| DateTime {
year,
month,
day,
hour: 0,
minute: 0,
second: 0,
};
assert_eq!(day(i32::MAX, 1, 1).write("dddd"), "Tuesday");
assert_eq!(day(i32::MIN, 1, 1).write("dddd"), "Tuesday");
assert_eq!(day(i32::MAX, 12, 31).write("dddd"), "Tuesday");
assert_eq!(day(-1, 1, 1).write("dddd"), "Friday");
assert_eq!(day(-1, 3, 1).write("dddd"), "Monday");
}
}