Getting all ISO weeks for a year #226
-
Hi there! First of all, let me say that I really enjoy My use case is that I want to aggregate some statistics for every week of a given target year. I need the weeks to always contain 7 days, so I think going for the ISO week date format is the correct choice. Here's a working version: use jiff::civil::ISOWeekDate;
fn main() {
let target_year = 2024;
let iso_week_date = ISOWeekDate::new(target_year, 1, jiff::civil::Weekday::Monday).unwrap();
let weeks_in_year = if iso_week_date.in_long_year() { 53 } else { 52 };
for week_number in 1..=weeks_in_year {
let start_of_week = ISOWeekDate::new(
iso_week_date.year(),
week_number,
jiff::civil::Weekday::Monday,
)
.unwrap();
let end_of_week = ISOWeekDate::new(
iso_week_date.year(),
week_number,
jiff::civil::Weekday::Sunday,
)
.unwrap();
println!(
"ISO week {}: {} - {}",
week_number,
start_of_week.date(),
end_of_week.date()
);
}
} Is there a better way to calculate this? C# offers a convenient function to get the number of weeks. Is there a specific design decision behind omitting this function? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
I see this as similar to I mostly kept ISO 8601 week date support pretty bare bones because I was unclear on how broadly used it was. But I'm generally happy to beef up the Another thing that would probably make this easier is adding an analog to And it probably makes sense to have use jiff::civil::ISOWeekDate;
fn main() {
let target_year = 2024;
let iso_week_date = ISOWeekDate::new(target_year, 1, jiff::civil::Weekday::Monday).unwrap();
let end = iso_week_date.last_of_year().unwrap(); // i think this has to be fallible? maybe not
for start_of_week in iso_week_date.series(1.week()).take_while(|&wd| wd <= end) {
let end_of_week = start_of_week.last_of_week().unwrap(); // i think also needs to be fallible
println!(
"ISO week {}: {} - {}",
start_of_week.week(),
start_of_week.date(),
end_of_week.date()
);
}
} Or something like that. Main I think I think is that the first-of/last-of routines might need to be fallible because I believe they can overflow Jiff's datetime limits. Kind of a bummer, but probably not a big deal. They would only fail near |
Beta Was this translation helpful? Give feedback.
I see this as similar to
Date::days_in_month
, so yeah, I'd be happy to haveISOWeekDate::weeks_in_year
.I mostly kept ISO 8601 week date support pretty bare bones because I was unclear on how broadly used it was. But I'm generally happy to beef up the
ISOWeekDate
type with more methods.Another thing that would probably make this easier is adding an analog to
Date::series
, but forISOWeekDate
. Then you could do something like this: https://docs.rs/jiff/latest/jiff/civil/struct.Date.html#example-how-many-times-do-i-mow-the-lawn-in-a-yearAnd it probably makes sense to have
ISOWeekDate::{first_of_week,last_of_week,first_of_year,last_of_year}
as well. If you combine those withISOWeekDate::s…