From 07a42f9f49e9e89ffb97988f06fa724c3dcc8911 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Mon, 6 Jan 2025 14:28:41 +0100 Subject: [PATCH] Add Month::num_days() --- src/month.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/month.rs b/src/month.rs index f964f85d8..ee5aa910f 100644 --- a/src/month.rs +++ b/src/month.rs @@ -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. @@ -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 { + 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 for Month { @@ -438,4 +462,11 @@ mod tests { let bytes = rkyv::to_bytes::<_, 1>(&month).unwrap(); assert_eq!(rkyv::from_bytes::(&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)); + } }