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

1 Answer

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

// Return all last Fridays of each month in a given year
fn last_fridays_of_year(year: i32) -> Vec<NaiveDate> {
    let mut dates = Vec::new();

    for month in 1..=12 {
        // Last day of the month
        let mut date = NaiveDate::from_ymd_opt(year, month, 1)
            .unwrap()
            .with_day(1)
            .unwrap()
            .with_month(month + 1)
            .unwrap_or_else(|| NaiveDate::from_ymd_opt(year + 1, 1, 1).unwrap())
            .pred_opt()
            .unwrap();

        // Walk backward to Friday
        while date.weekday().num_days_from_monday() != 4 {
            date = date.pred_opt().unwrap();
        }

        dates.push(date);
    }

    dates
}

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

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

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



/*
run:

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

*/

 



answered May 24 by avibootz

Related questions

...