Skip to content

Javascript SetMonth Issue

I am doing unit tests.

  it("Month calculate", () => {
    const baseDate = new Date("2015-02-15T12:00:00.000Z");
    baseDate.setMonth(baseDate.getMonth() + 1)
    expect(baseDate.toISOString()).toBe("2015-03-15T12:00:00.000Z")
  })

On my local node process I get this error

Expected: "2015-03-15T12:00:00.000Z"
Received: "2015-03-15T13:00:00.000Z"

On docker node process it works.

I believe it is related to the DST, but I don’t understand how…

Answer

You’re right that DST is coming into play, because you’re using the local time setMonth/getMonth methods, so DST comes into it (adding the month, the Date object takes DST into account to avoid changing the time-of-day; but when you look at the result in UTC, you see the time is off by the DST offset, since it was local time math that applied to the increment). To work in UTC like the rest of your code, use setUTCMonth/getUTCMonth instead.

it("Month calculate", () => {
    const baseDate = new Date("2015-02-15T12:00:00.000Z");
    baseDate.setUTCMonth(baseDate.getUTCMonth() + 1)
    expect(baseDate.toISOString()).toBe("2015-03-15T12:00:00.000Z")
})

Likely your docker node is working UTC, or at least in a time zone where DST doesn’t change during that month (it doesn’t here in the UK, for instance; we don’t change until later in March). But in your local timezone, apparently DST occurs during that month, so you see the issue locally but not on the docker node.