How to find the dates of the last Sunday of each month of a given year in Rust

1 Answer

0 votes
use chrono::{Datelike, Duration, NaiveDate};
use std::env;

// Return all last Sundays of each month in a given year
struct LastSundaysOfYear {
    year: i32,
    month: u32,
}

impl LastSundaysOfYear {
    fn new(year: i32) -> Self {
        LastSundaysOfYear { year, month: 1 }
    }
}

impl Iterator for LastSundaysOfYear {
    type Item = NaiveDate;

    fn next(&mut self) -> Option<Self::Item> {
        if self.month > 12 {
            return None;
        }

        let year = self.year;
        let month = self.month;

        // Last day of the month
        let mut date = NaiveDate::from_ymd_opt(year, month, 1)
            .unwrap()
            .with_day(1)
            .unwrap()
            .checked_add_months(chrono::Months::new(1))
            .unwrap()
            - Duration::days(1);

        // Walk backward to Sunday
        while date.weekday().num_days_from_sunday() != 0 {
            date = date - Duration::days(1);
        }

        self.month += 1;
        Some(date)
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();

    let year: i32 = if args.len() > 1 {
        args[1].parse().unwrap_or(2026)
    } else {
        2026
    };

    for date in LastSundaysOfYear::new(year) {
        println!("{}", date.format("%m/%d/%Y"));
    }
}



/*
run:

01/25/2026
02/22/2026
03/29/2026
04/26/2026
05/31/2026
06/28/2026
07/26/2026
08/30/2026
09/27/2026
10/25/2026
11/29/2026
12/27/2026

*/

 



answered 9 hours ago by avibootz

Related questions

...