Search code examples
javascriptnode.jstypescriptdateutc

Why I canot get the same result using the getDay() method and the getUTCDay() method on the Javascript Date object


Today we are Monday it's 00:51 am I am from Quebec city and therefor I am in GMT-0500 (UTC−05:00)

I dont know why the code below gives me 2 different results :

const weekday = Array('sunday', 'monday', 'tuesday', 'wednesday', 
                      'thursday', 'friday', 'saturday');

console.log('getDay() =', weekday[new Date('2019-02-18').getDay()]); 
  // getDay() = sunday

console.log('getUTCDay() =', weekday[new Date('2019-02-18').getUTCDay()]); 
  // getUTCDay() = monday

On the MDN web site they say The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.

And they say exactly the same for The getUTCDay() method returns the day of the week in the specified date according to universal time, where 0 represents Sunday.

The only difference is one is according to local time and the other one is according to universal time...

I am not sure what I should verify to understand the difference I tried both in Node.js (Typescript) and in the console Chrome DevTools (Javascript)

In my computer settings the first day of a week is Sunday...


Solution

  • new Date(string) uses Date.parse() to parse the date.

    From the Date.parse() docs:

    When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.

    Therefore, the date created by new Date('2019-02-18') will be exactly midnight on Feb 18, 2019 in UTC time.

    If you are in a timezone with a negative offset then that date will actually be Sunday in local time (Quebec City is at GMT-0500 so that date is 2019-02-17:19:00:00 local time).

    So if you are in a time zone with a negative offset then .getDay() is correctly returning 0 for Sunday, while .getUTCDay() is correctly returning 1 for Monday.