Skip to content

Comment on Fix date-handling bug when today’s date is later than the target month

Comments

I've seen somebody write this exact bug before! Hah. Like, something to the effect of

    var newDate = new Date(GetDate().Year, GetDate().Month + 1, GetDate().Day);
but with extra logic to ensure that the Month component wrapped around.
but with extra logic to ensure that the Month component wrapped around

Extra unnecessary logic. The functionality that causes this bug is so you don't need to handle wraparound yourself:

  >> new Date(2023, 12, 1)
  Date Mon Jan 01 2024 00:00:00 GMT-0600 (Central Standard Time)
(Note months are 0-indexed so 12 is one past the last month of the year)

It works with negative numbers too, to wrap backwards:

  >> new Date(2024, -1, 1)
  Date Thu Dec 01 2023 00:00:00 GMT-0600 (Central Standard Time)

Depends on the language/library. C#'s DateTime will throw ArgumentOutOfRangeException.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.