Search code examples
javascriptdateutcdst

Setting UTC date seems to be using daylight savings


When I try to add to my date's months it is skipping November. I believe this to be because of November's daylight savings.

Here is the code that shows that it is jumped one day futher than I want:

var my_date = new Date(1377993599000);
console.log(my_date.toUTCString());

This outputs "Sat, 31 Aug 2013 23:59:59 GMT"

my_date.setUTCMonth(my_date.getUTCMonth() + 3);
console.log(my_date.toUTCString());

This outputs "Sun, 01 Dec 2013 23:59:59 GMT"

And now, when I try to only add 2:

my_date.setUTCMonth(my_date.getUTCMonth() + 2);
console.log(my_date.toUTCString());

This outputs "Thu, 31 Oct 2013 23:59:59 GMT"

When I try to set the date to zero:

my_date.setUTCMonth(my_date.getUTCMonth() + 3, 0);
console.log(my_date.toUTCString());

This outputs "Thu, 31 Oct 2013 23:59:59 GMT"

Does anyone know a clean trick for fixing this?

Am I better off ditching the UTC functions and simply removing the timezone offset from all the times? If I did this would it actually fix my problem?


Solution

  • There's no 31 November, so when you add 3 to the months it has no choice but to roll over to the next month, making it 1 December.

    The problem of reliably moving forward by months is tricky. You can set the day-of-month (.setDate()) to 1 before doing it, but then you've got to decide how to set it back to something relevant to the original date.