Home > front end >  is javascript new Date() created at same time on 2 diff machines/timezones exactly same?
is javascript new Date() created at same time on 2 diff machines/timezones exactly same?

Time:10-04

I wanted to know if a date object created at any point of time differ based on time zones or not. I tried this by executing new Date().getTime() once for IST and immediately again by setting my PC time zone to GMT. The resultant values are:

  • IST - 1633334780053
  • GMT - 1633334788831

A difference of around 8000 milliseconds

From this it seems that datetime objects created at same moment are exactly same no matter in which time zone they are created. Please suggest if this understanding is correct or is there more to it.

CodePudding user response:

You're right. Two different date time objects created at the same point of time are same no matter the time zone.

They can be formatted to their corresponding timezone representation using javascript.

One important thing to be noted is that the date time object created uses the system's date time configuration to find the correct time. If the system's date and time configurations are correct and in sync, then the date time object created in the browser will be correct and will match the system time at the time of creating that object.

CodePudding user response:

This is detailed in the JavaScript specification: https://tc39.es/ecma262/#sec-date-objects.

More information is in the MDN docs Date.getTime():

The getTime() method returns the number of milliseconds* since the Unix Epoch.

*JavaScript uses milliseconds as the unit of measurement, whereas Unix Time is in seconds.

getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.

So Date.getTime() will always return the number of milliseconds since 1970-01-01 00:00:00 UTC, regardless of the client / machine timezone setting.

  • Related