Is there a idiomatic Rust way to get the number of days in a given month? I've looked at chrono but I haven't found anything in the docs for this.
I'm looking for something that can manage leap years similar to calendar.monthrange
in Python or DateTime.DaysInMonth
in C# .
pub fn get_days_from_month(year: i32, month: u32) -> i64 {
NaiveDate::from_ymd(
match month {
12 => year + 1,
_ => year,
},
match month {
12 => 1,
_ => month + 1,
},
1,
)
.signed_duration_since(NaiveDate::from_ymd(year, month, 1))
.num_days()
}
You can use NaiveDate::signed_duration_since
from the chrono
crate:
use chrono::NaiveDate;
fn main() {
let year = 2018;
for (m, d) in (1..=12).map(|m| {
(
m,
if m == 12 {
NaiveDate::from_ymd(year + 1, 1, 1)
} else {
NaiveDate::from_ymd(year, m + 1, 1)
}.signed_duration_since(NaiveDate::from_ymd(year, m, 1))
.num_days(),
)
}) {
println!("days {} in month {}", d, m);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With