moment / luxon

⏱ A library for working with dates and times in JS
https://moment.github.io/luxon
MIT License
15.12k stars 728 forks source link

Reliable method for next / previous weekday #1517

Open thomassth opened 9 months ago

thomassth commented 9 months ago

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

mrlubos commented 9 months ago

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.

diesieben07 commented 9 months ago

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.

shashankbhat10 commented 9 months ago

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

diesieben07 commented 9 months ago

Of course, go ahead @shashankbhat10