48

If JavaScript (new Date()).getTime() is run from 2 different timezones simultaneously, will you get the same value?

Will this value be affected by the system time set on the machine where the browser is running?

Gottlieb Notschnabel
  • 9,408
  • 18
  • 74
  • 116
user855
  • 19,048
  • 38
  • 98
  • 162

4 Answers4

52

Yes, it's affected by system time. However, if the local time is correct (for whatever time zone the computer's set to), it should be the same in any time zone.

The ECMAScript standard says (§15.9.1.1):

"Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC."

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
28

Code:

var today = new Date();
console.log(today);
var t = today.getTime();
console.log(t);

My Computer in the UK:

Sat Sep 21 2013 03:45:20 GMT+0100 (GMT Daylight Time)
1379731520112 

My VPS:

Sat, 21 Sep 2013 02:44:31 GMT
1379731471743

Difference between getTime values is 48,369 milliseconds (48s) out of sync not the 1 hour zone difference

acheo
  • 3,106
  • 2
  • 32
  • 57
8

You won't get the same value - difference between two client's browsers picking up their system time, but if their time is set up ok, you should get two times with a minimal difference since getting the timestamp using new Date(), you can get the UTC value (new Date() returns number of milliseconds ellapsed since January 1, 1970, and that won't change), which is universal time and is location agnostic.

darioo
  • 46,442
  • 10
  • 75
  • 103
2

There will most likely always be a deviation between times attained between machines, but (I was wrong before) JavaScript Date() takes the UTC timezone as default.

Usually when time is essential, it's best to simply use the Server time and apply timezone corrections to that in the output if required.

BGerrissen
  • 21,250
  • 3
  • 39
  • 40
  • This is incorrect. As long as local time is correct, time zone doesn't matter. – Matthew Flaschen Jan 02 '11 at 09:30
  • 2
    He's talking about different timezones which will have differing local times unless someone elected to offset his local time from his timezone to correspond with another timezone. – BGerrissen Jan 02 '11 at 09:33
  • `getTime` does not return the local time, though. As long as the local time is set correctly (for whatever time zone the computer's in), the UTC time returned by `getTime` will also be correct. – Matthew Flaschen Jan 02 '11 at 09:38
  • How sure are you it does not return local time? I just checked its value in w3schools where uses the non UTC Date time in javascript and it returns the time in my timezone. Not the UTC timezone – aj go Nov 06 '21 at 09:13