Skip to content Skip to sidebar Skip to footer

What Time Zone Does The JavaScript New Date() Use?

I have a C# application that return in JSON an expiration date of an authentication token like this: 'expirationDate':'Fri, 27 Mar 2015 09:12:45 GMT' In my TypeScript I check that

Solution 1:

JavaScript will use the client's local time but it also has UTC / GMT methods. The following is from Mozilla:

The JavaScript Date object supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where JavaScript is executed.

While methods are available to access date and time in both UTC and the localtime zone, the date and time are stored in the local time zone:

Note: It's important to keep in mind that the date and time is stored in the local time zone, and that the basic methods to fetch the date and time or its components all work in the local time zone as well.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date


Solution 2:

As other said, JavaScript uses clients system time, but you can create date object from server time, so every client will get the same current time.

var date = new Date("<?php echo date("Y-m-d H:i:s");?>");

It will work only on page load. If you want to check later for dates still valid, then you need to synchronize current date with server date every couple of seconds.


Solution 3:

What time zone does the Javascript new Date() use?

Date objects work with the number of milliseconds since The Epoch (Jan 1st 1970 at midnight GMT). They have methods like getDay and getMonth and such that use the local timezone of the JavaScript engine, and also functions like getUTCDay and getUTCMonth that use UTC (loosely, GMT).

If you're parsing a string, you need to be sure that the string is in a format that Date knows how to parse. The only defined format in the specification is a simplified derivative of ISO-8601, but it was only added in ES5 and they got it wrong in the spec about what should happen if there's no timezone indicator on the string, so you need to be sure to always have a timezone indicator on it (for now, ES6 will fix it and eventually engines will reliably use ES6 behavior). Those strings look like this:

"2015-03-27T09:32:54.427Z"

You can produce that format using the toISOString method.


Solution 4:

By default, JS will use your browser timezone, but if you want to change the display, you can for example use the toString() function ;)

var d1=new Date();
d1.toString('yyyy-MM-dd');       //returns "2015-03-27" in IE, but not FF or Chrome
d1.toString('dddd, MMMM ,yyyy')  //returns "Friday, March 27,2015" in IE, but not FF or Chrome

Post a Comment for "What Time Zone Does The JavaScript New Date() Use?"