Recently I wrote some code for picking recurring dates. If it's supposed to recur monthly on a day that is acceptable in some months (January 31st) but not in others (January 31st) then it instead will happen on the last day of the month.
Currently I'm resorting to the following:
fn with_day_saturated<Tz: chrono::TimeZone>(datetime: DateTime<Tz>, day: u32) -> DateTime<Tz> {
let day = day.clamp(1, 31);
if datetime.day() == day {
return datetime;
}
// We check back up to 3 days, because non-leap year February is the worst
// case scenario. 31 - 3 = 28, which guarantees that we end up in bounds.
datetime
.with_day(day)
.or_else(|| datetime.with_day(day - 1))
.or_else(|| datetime.with_day(day - 2))
.or_else(|| datetime.with_day(day - 3))
.unwrap()
}
...which is obviously not ideal. 😅
It'd be great if there was some better way to figure out what the last day of the current month was. I could use that in the .clamp instead and delete half of this code.
Recently I wrote some code for picking recurring dates. If it's supposed to recur monthly on a day that is acceptable in some months (January 31st) but not in others (January 31st) then it instead will happen on the last day of the month.
Currently I'm resorting to the following:
...which is obviously not ideal. 😅
It'd be great if there was some better way to figure out what the last day of the current month was. I could use that in the
.clampinstead and delete half of this code.