Skip to content

Commit

Permalink
Add Month::num_days()
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Jan 6, 2025
1 parent 8b86349 commit 07a42f9
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/month.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use core::fmt;
#[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
use rkyv::{Archive, Deserialize, Serialize};

use crate::naive::NaiveDate;
use crate::OutOfRange;

/// The month of the year.
Expand Down Expand Up @@ -161,6 +162,29 @@ impl Month {
Month::December => "December",
}
}

/// Get the length in days of the month
///
/// Yields `None` if `year` is out of range for `NaiveDate`.
pub fn num_days(&self, year: i32) -> Option<u8> {
Some(match *self {
Month::January => 31,
Month::February => match NaiveDate::from_ymd_opt(year, 2, 1)?.leap_year() {
true => 29,
false => 28,
},
Month::March => 31,
Month::April => 30,
Month::May => 31,
Month::June => 30,
Month::July => 31,
Month::August => 31,
Month::September => 30,
Month::October => 31,
Month::November => 30,
Month::December => 31,
})
}
}

impl TryFrom<u8> for Month {
Expand Down Expand Up @@ -438,4 +462,11 @@ mod tests {
let bytes = rkyv::to_bytes::<_, 1>(&month).unwrap();
assert_eq!(rkyv::from_bytes::<Month>(&bytes).unwrap(), month);
}

#[test]
fn num_days() {
assert_eq!(Month::January.num_days(2020), Some(31));
assert_eq!(Month::February.num_days(2020), Some(29));
assert_eq!(Month::February.num_days(2019), Some(28));
}
}

0 comments on commit 07a42f9

Please sign in to comment.