8

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).

mcarton
  • 27,633
  • 5
  • 85
  • 95
Florian sp1rit
  • 575
  • 1
  • 7
  • 20

2 Answers2

8

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.

harmic
  • 28,606
  • 5
  • 67
  • 91
7

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.

Kilerd Chan
  • 151
  • 1
  • 2
  • 5