How to get the system date in Javascript?

Asked

Viewed 1,204 times

5

It’s a simple question I imagine, I’m starting my studies in Javascript and would like to know how to get the date of the computer (year, month, day, hour, minute and second).

Also, does the date already come with a time zone? If not, how can I convert?

  • 1

    Will the Date clase not suit you? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

  • As I had said I’m starting rs, I just saw, attend me yes, thank you!

  • Oops, show, good studies! :)

  • 1

    On "already comes with time zone", maybe this helps: https://answall.com/a/455444/112052

3 answers

7


You can use Date, but as you mentioned a concern with the time zone, there are some details to note.

Contrary to what the another answer, one Date won’t come in the time zone the device is configured. Actually, Date has no information about the time zone (see more details on language specification).

As explained here, the Date actually represents a timestamp: the quantity of milliseconds since the Unix Epoch (which in turn amounts to 1970-01-01T00:00Z - January 1, 1970 at midnight, at UTC).

That is, the Date represents a unique moment, a point in the timeline. Think of "now": at this very moment, what day is today and what time is it? In each part of the world, the answer will be different (in some parts of the world, it is June 10, in others it may be June 9 or 11, and the time will also be different). Although the date and time are different, the instant (the value of the timestamp) is the same for everyone. And the Date only saves timestamp information.

When you print the date (via alert or console.log) or when it obtains information from it (via getters or toString()), this timestamp is converted to the time zone that is configured in the environment where the code is running. That is, the Date uses the time zone setting to convert the timestamp to the correct date and time values. But the Date "does not come" with the time zone. It is a subtle but important difference to understand how to use it.

To illustrate better, I ran the following test on Chrome running on Windows (the behavior may not be the same on other browsers and/or operating systems):

  • open the console (press F12)

  • create a date and print:

      let d = new Date();
      console.log(d);
    
  • the result will show the current date and time, in the time zone that is configured in Windows

  • enter Windows settings and change the time zone (preferably to "distant" places such as Europe or Asia, so the difference is clearer)

  • back to the Chrome console and only print the date again (without creating a new one): console.log(d)

  • the current date and time will be displayed in the new time zone

All without changing the object Date. If it "already came" with the time zone, the change in the environment would not affect the output. But the Date does not store the time zone information, it only uses the time zone that is configured in the environment at certain times (for example, when the date is printed on the console), to convert the timestamp to the respective date and time values.

Already testing in Firefox, the behavior was different: it loads the time zone of the OS when it starts and then does not update anymore. That is, I create a date and it is shown in the time zone that is configured. If I change the time zone, it is useless to create new instances of Date, that they will be shown on the spindle that was configured at the time the browser was started (and only by restarting the browser to get the new configuration).


And that’s because we only test on 2 different browsers. But if we test on Node, for example, you can overwrite the time zone in several ways:

  • on Linux, you can set the environment variable TZ at the command line:

      TZ=Asia/Tokyo node teste.js 
    
  • or in the JS file itself, change the process.env.TZ. Ex: process.env.TZ = 'Asia/Tokyo' - this overwrites the variable TZ and any OS configuration.

For example, the code below:

d = new Date();

process.env.TZ = 'Europe/Berlin';
console.log(d.toString());
console.log(d.getHours());

process.env.TZ = 'Pacific/Apia';
console.log(d.toString());
console.log(d.getHours());

Running on the Node (from version 13, if I’m not mistaken, because previously only worked if the variable was set at the beginning of the script, and mid-script changes were not effective), the output is (running at 09:06 of the day 10/06/2020, Time of Brasilia):

Wed Jun 10 2020 14:06:18 GMT+0200 (Central European Summer Time)
14
Thu Jun 11 2020 01:06:18 GMT+1300 (Apia Standard Time)
1

Note: the above code was tested on Linux, for setar process.env.TZ did not work on Windows Node

That is, the same object Date results in different dates and times depending on the time zone that is configured at a time when toString() and getHours() are called. If the Date "already came" with the time zone, it would not be affected by this configuration change.


If you want the date and time to be specific to a time zone, independent of environment configuration, unfortunately Javascript does not provide many alternatives. The most we have is toLocaleString, that can receive a Timezone:

d.toLocaleString('en', { timeZone: 'America/Sao_Paulo' });

Thus, the date and time will always take into account the indicated Timezone, regardless of what is configured in the environment. But the problem is that the format will always be dependent on the locale (the first parameter, which you can change from en for pt-BR, for example, if you want the Brazilian date format). But if you only want the day, or only the time, it is useless to use the getters, because they are limited to the zone configured in the environment.

Another alternative is to use an external library, such as Moment js.. To work with time zones, you will also need the Moment Timezone. Thus, you can create dates referring to any Timezone, without being affected by the setting of the environment. On Node, for example, would look like this:

let moment = require('moment-timezone');
let d = moment.tz('America/Sao_Paulo');

// mudar a configuração de timezone não afeta o Moment
process.env.TZ = 'Europe/Berlin';
console.log(d.format());
console.log(d.hour());

// mudar a configuração de timezone não afeta o Moment
process.env.TZ = 'Pacific/Apia';
console.log(d.format());
console.log(d.hour());

// converter para outro timezone
d.tz('Europe/Berlin');
console.log(d.format());
console.log(d.hour());

Thus the moment created preserves Timezone information (it does "already" with the Timezone that is informed at the time it is built), and the changes in the environment do not affect its date and time. Only when making an explicit conversion to another Timezone, the date and time values are updated. The exit code above is (rotated at 09:16 of the day 10/06/2020, Time of Brasilia):

2020-06-10T09:16:18-03:00
9
2020-06-10T09:16:18-03:00
9
2020-06-10T14:16:18+02:00
14

If you want to use Timezone configured in the environment, just call moment.tz() no parameters. You can also get the possible environment Timezone using moment.tz.guess() (yes, the name is that same, "guess" - read the documentation link to understand why it is not always possible to be sure and so it tries to guess the environment Timezone).

And if you need the Date, it is possible to convert by doing d.toDate() - just remembering that as it returns a Date, all Timezone information is lost.


It is worth remembering that the other statement made in the aforementioned answer is also not 100% true: the fact that the Time of Brasilia will always be 3 hours behind UTC. This is worth most of the time, but during daylight saving time, it changes from UTC-3 to UTC-2. All right that currently (2020) we do not have summer time in Brazil, but as it is defined by the government and politicians change their minds all the time (not always with technical motivations), nothing guarantees that it will not return in the future. So don’t count on it (which will always be -3).

This is another advantage of using a dedicated API like Moment.js, as it has all the history of changes, and using timezones like America/Sao_Paulo, it will always seek the correct values (as long as it is updated, of course, because as I said, these data change all the time). Of course, if your system is up-to-date, the browser will also have the correct information when displaying the date. Using an external lib depends more on what you need (if you don’t want to depend on your environment settings, for example, it might be worth it).

Anyway, notice that "getting the date from the computer" doesn’t seem as simple as you thought. The "computer date" itself depends on what is configured in the OS, and yet we saw that it is possible to override this setting. It all depends on what you need, but anyway the alternatives are there, choose the one that is most suitable for your case.


See more on the subject here and here.

  • 1

    Very good guy, explained everything he needed and even more! Thank you very much! Better explanation

4

The date is already in the time zone that the device is configured. If it is configured for Brasilia time, for example, it will be UTC (Coordinated Universal Time) -3 o'clock.

To catch year, month, day, hour, minute and second you use the object new Date():

var hoje = new Date();
var ano = hoje.getFullYear();
var mes = hoje.getMonth();
var dia = hoje.getDate();
var hora = hoje.getHours();
var minuto = hoje.getMinutes();
var segundo = hoje.getSeconds();

console.log("Ano:",ano+", Mês:",mes+", Dia:",dia+", Hora:",hora+", Minuto:",minuto+", Segundo:",segundo);

Recalling that the month value starts at 0 (January is 0, February is 1, March is 2 etc.). If you want to get the month value in the calendar, you need to add +1:

var mes = hoje.getMonth()+1;

3

Browser other questions tagged

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