3

I have two date strings - same month, day and time, but different year (2017, 1970). When I convert them to Date object and then use getDate() function, I get different day.

var d1 = '1970-05-11T22:00:00.000Z';
var d2 = '2017-05-11T22:00:00.000Z';
console.log(new Date(d1), new Date(d1).getDate()); // day 11
console.log(new Date(d2), new Date(d2).getDate()); // day 12

Why is that so and how can I control this behavior?

9
  • 4
    I get 11 for both. What timezone are you in, and did the rules for Daylight Savings change between 1970 and 2017 where you are? Commented Oct 19, 2017 at 11:03
  • 1
    can you console.log(new Date(d1) + '', new Date(d1).getDate()); and console.log(new Date(d2) + '', new Date(d2).getDate()); - I suspect daylight saving issue too Commented Oct 19, 2017 at 11:03
  • 1
    I get 12 for both :p because Australia Commented Oct 19, 2017 at 11:04
  • 1
    getDate() converts to whatever timezone is configured in your browser. You can alternatively use getUTCDate() instead
    – user7605325
    Commented Oct 19, 2017 at 11:06
  • 2
    That explains it then - from here: "Daylight Saving Time (DST) Not Observed in Year 1970 ... Prague observed Central European Time (CET) all year." Commented Oct 19, 2017 at 11:10

1 Answer 1

5

Your profile indicates that you're in the Czech Republic. getDate returns values for the local time. In 2017, according to timeanddate.com, Daylight Savings was observed and was in effect in May. However, it also says that during 1970:

Daylight Saving Time (DST) Not Observed in Year 1970

Prague observed Central European Time (CET) all year.

DST was not in use in 1970.

The 22:00 in your UTC times is close enough to midnight for getDate to return the next day in your timezone, since it was the 12th local time in 2017, but still the 11th in 1970.

You can fix this by using getUTCDate instead, which returns 11 for both:

var d1 = '1970-05-11T22:00:00.000Z';
var d2 = '2017-05-11T22:00:00.000Z';
console.log(new Date(d1), new Date(d1).getUTCDate()); // day 11
console.log(new Date(d2), new Date(d2).getUTCDate()); // day 11

1
  • Worth noting that it is only since ECMAScript 2015 (ed 6) that implementations have been expected to make their "best effort" to determine historical daylight saving changes.
    – RobG
    Commented Oct 19, 2017 at 20:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.