How to get the last Friday of every Month for next 12 months using chrono?

544 Views Asked by At

How can I get the last Friday of each month for the next N months in Rust? I am able to get every Friday for the next N weeks but not able to find out how to determine if it is the last Friday of a month.

Currently I have:

use chrono::{Date, Datelike, DateTime, Duration, NaiveDate, NaiveDateTime, Utc, Weekday};

...

while index < 52 {
    // Works to get friday at midnight
    let new_date = NaiveDate::from_isoywd_opt(
        now.iso_week().year(),
        now.iso_week().week(),
        Weekday::Fri
    ).unwrap();
    let naive_datetime: NaiveDateTime = new_date.and_hms(0, 0, 0);

    log::debug!("{:#?}", naive_datetime);

    now = now + Duration::weeks(1);
    index += 1;
}

But strangely I cannot find an easy way to determine the month cadence for this. I must be missing something obvious.

1

There are 1 best solutions below

1
On

I was able to get it to work with the hint from @Jmb with this code block.

while index < 52 {
    let year = now.iso_week().year();
    let month = now.month();
    let week = now.iso_week().week();

    // Works to get friday at midnight
    let new_date = NaiveDate::from_isoywd_opt(
        year,
        week,
        Weekday::Fri,
    ).unwrap();
    let naive_datetime: NaiveDateTime = new_date.and_hms(0, 0, 0);

    if naive_datetime.day() < 7 {
        let previous_friday = naive_datetime - Duration::weeks(1);
        let datetime: DateTime<Utc> = Utc.from_utc_datetime(&previous_friday);
        dates.push(datetime);
    }

    now = now + Duration::weeks(1);
    index += 1;
}

log::debug!("{:#?}", dates);