How to get the start and the end of date for each month with NaiveDate?

How to get the last date of a month with chrono::NaiveDate. I try to search the manual but can't found anything useful.

   use chrono::{NaiveDate, Datelike};

   // from January to December m = 1 - 12
   for m in 1..=12 {
        let end = ..... ?? 
        let start_date = NaiveDate::from_ymd(year, m, 1);  /// each month starts with 1
        let end_date = NaiveDate::from_ymd(year, m, end); /// here's the problem
        container.push((start_date, end_date));
   }

the closest would be to use Datelike::day function and subtract 1 day from it. chrono::Datelike - Rust
but I don't know how to use it with NaiveDate

You can subtract a Duration

Playground

use chrono::{Duration, NaiveDate};

fn main() {
    let june_first = NaiveDate::from_ymd(2022, 6, 1);

    let may_end = june_first - Duration::days(1);

    println!("{june_first} {may_end}");
}
4 Likes