use chrono::Datelike;
use chrono::NaiveDate;
pub trait DateTimeFormatExt {
fn format_yymmdd(&self) -> String;
}
impl DateTimeFormatExt for NaiveDate {
fn format_yymmdd(&self) -> String {
let yy = self.year().rem_euclid(100);
let mm = self.month();
let dd = self.day();
format!("{:02}{:02}{:02}", yy, mm, dd)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_year_2023() {
let d = NaiveDate::from_ymd_opt(2023, 5, 9).unwrap();
assert_eq!(d.format_yymmdd(), "230509");
}
#[test]
fn format_year_2000() {
let d = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
assert_eq!(d.format_yymmdd(), "000101");
}
#[test]
fn format_year_1999() {
let d = NaiveDate::from_ymd_opt(1999, 12, 31).unwrap();
assert_eq!(d.format_yymmdd(), "991231");
}
#[test]
fn format_pads_single_digit_month_and_day() {
let d = NaiveDate::from_ymd_opt(2005, 3, 7).unwrap();
assert_eq!(d.format_yymmdd(), "050307");
}
#[test]
fn format_century_boundary() {
let d = NaiveDate::from_ymd_opt(2100, 6, 15).unwrap();
assert_eq!(d.format_yymmdd(), "000615");
}
#[test]
fn format_length_is_always_six() {
let dates = [
NaiveDate::from_ymd_opt(2000, 1, 1).unwrap(),
NaiveDate::from_ymd_opt(1985, 11, 22).unwrap(),
NaiveDate::from_ymd_opt(2030, 9, 5).unwrap(),
];
for d in &dates {
assert_eq!(d.format_yymmdd().len(), 6, "Expected 6 chars for {:?}", d);
}
}
}