Creating Date by passing numbers has different result from passing a string with the same values

Asked

Viewed 48 times

2

I’m studying the dates part of Javascript and saw something I can’t explain.

Follows the code:

var envio = new Date(2018, 02, 20);
var envio2 = new Date("2018-02-20");

console.log("Virgula: " + envio);
console.log("String: " + envio2);

The result that brings me:

Virgula: Tue Mar 20 2018 00:00:00 GMT-0300 (Horário Padrão de Brasília) scripts.js:489:13
String: Mon Feb 19 2018 21:00:00 GMT-0300 (Horário Padrão de Brasília)

I understood that in the case of the month, the comma version, counts from scratch, but I did not understand why in the string version, be with the day 19.

Does anyone know what might be going on?

1 answer

3

When you call the builder passing numbers, the month is indexed at zero (January is zero, February is 1, etc). So new Date(2018, 02, 20) corresponds to March 20. If you want February 20, do new Date(2018, 1, 20).

Another detail is that it sets the time to midnight in the time zone of the environment in which it is running (in the case of browser, generally it uses the one of the operating system). Therefore in its test the result was March 20 at midnight in the Schedule of Brasilia (this excerpt from the documentation says that the uninformed fields - in this case, the hour, minute and second - are set to zero, so the time is midnight).

When you pass a string on ISO 8601 format containing only the date (without the time), the month is indexed at 1 (January is 1, February is 2, etc.) and the time is set to midnight at UTC (which, in turn, corresponds to 9 the night of the previous day in Brasilia Time, since the Brasilia Time is 3 hours behind the UTC - or 2 hours, when it is daylight saving time). But when you print the date, it is shown in the browser’s time zone, so it shows the 19th of February at 9:00 pm (because the 19th at 9:00 pm in Brasília Time is equivalent to the 20th at midnight in UTC).

To be more precise, the documentation cites that when passing a string to the constructor of Date, it uses the same logic as the method parse. And this, in turn, uses these rules (and this link is described what I have already said above: "date-only Forms are Interpreted as a UTC time and date-time Forms are Interpreted as local time").


That is, if you put the time in the string, then it considers the browser time zone:

// sem horário, considera meia-noite em UTC
console.log('UTC: ' + new Date("2018-02-20"));

// com horário, considera o fuso horário do browser
console.log('Fuso do browser: ' + new Date("2018-02-20T00:00"));

This all happens because the Date Javascript actually represents a timestamp (a point in the timeline), not a specific date (a single value of day, month, year, hour, minute and second).

For more details, read here, here, here, here and here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.