luxon
luxon copied to clipboard
Reliable method for next / previous weekday
Describe the bug DateTime.set({ weekday: X }) sometimes returns a date in the past, and sometimes in the future. To Reproduce
luxon.DateTime.fromISO('2023-10-01T20:24:00Z').set({ weekday: 3 }).toISO()
>'2023-09-27T16:24:00.000-04:00'
luxon.DateTime.fromISO('2023-10-02T20:24:00Z').set({ weekday: 3 }).toISO()
>'2023-10-04T16:24:00.000-04:00'
Actual vs Expected behavior All values return a future date
Additional context I think in moment.js, setting a weekday will always return a future date
This sounds like an expected behaviour. You're setting day of the current week, so it can be both in the future and in the past.
A reliable way to do this would be:
function nextWeekday(date, weekday) {
return date.plus({days: (7 - date.weekday + weekday) % 7});
}
I'll mark this as a feature request to potentially introduce DateTime#nextWeekday
and DateTime#previousWeekday
methods.
Hey @diesieben07 , can I raise a PR for this. Have added the suggested methods and respective tests.
Of course, go ahead @shashankbhat10