luxon icon indicating copy to clipboard operation
luxon copied to clipboard

Reliable method for next / previous weekday

Open thomassth opened this issue 1 year ago • 4 comments

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

thomassth avatar Oct 03 '23 15:10 thomassth

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.

mrlubos avatar Oct 04 '23 10:10 mrlubos

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.

diesieben07 avatar Oct 04 '23 16:10 diesieben07

Hey @diesieben07 , can I raise a PR for this. Have added the suggested methods and respective tests.

shashankbhat10 avatar Oct 06 '23 22:10 shashankbhat10

Of course, go ahead @shashankbhat10

diesieben07 avatar Oct 07 '23 09:10 diesieben07