Get date of start/end of week

3.3k Views Asked by At

I'm need the chrono::Date of the first and last date of a week from the current year.

I have two issues, first I'm unable to get chrono to parse the week of current year and second I'm unable to get the first/last date of the week. (There are a lot of solutions for other languages here, but not rust)

TLDR: I need a function like this: fn x(week: isize) -> (Date<Local>, Date<Local>) with the tuple being (first day of week, last day of week).

2

There are 2 best solutions below

0
On BEST ANSWER

If I have understood your question correctly, you can use something like this:

use chrono::{NaiveDate, Weekday, Datelike};

fn week_bounds(week: u32) -> (NaiveDate, NaiveDate) {
    let current_year = chrono::offset::Local::now().year();
    let mon = NaiveDate::from_isoywd(current_year, week, Weekday::Mon);
    let sun = NaiveDate::from_isoywd(current_year, week, Weekday::Sun);
    (mon, sun)
}

Playground

That is assuming ISO8601 conventions (Monday as the first day and Sunday as the last, and ISO week numbering). It also returns NaiveDate instead of Date<Local>, which you could obtain using:

let date_time: DateTime<Local> = Local.from_local_datetime(&naive).unwrap();

if needed.

1
On

you can try my crate https://crates.io/crates/now , it provide very convenient method to get beginning or end of week.

use now::DateTimeNow;

let now = Utc::now();
now.beginning_of_week();

edit:

for chrono you can use datetime.iso_week().week() to get iso week number. or you can use now via datetime.week_of_year() which is a simple wrapper for preview method.