Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 the date is still valid here:

isAuthenticationExpired = (expirationDate: string): boolean => {
    var now = new Date().valueOf();
    var exp: any = Date.parse(expirationDate).valueOf();
    return exp - now <= 0;
};

What I would like to know is what time zone does new Date() use when it is returning a date?

like image 344
Alan2 Avatar asked Mar 27 '15 09:03

Alan2


People also ask

What timezone is new date in JavaScript?

The Date object in JavaScript does not store a time zone. It stores a timestamp that represents the number of milliseconds that have passed since midnight on January 1st, 1970.

Does new date () return local time?

Yes, the time returned by the new Date() expression doesn't consider timezone issues, only when it is converted to a string. My timezone is GMT-0200. As we can see, the time returned does not consider the timezone.

Does new date () return UTC?

new Date() returns relative time and not UTC time.

What is the default time zone in JavaScript?

Sometimes, we may want to initialize a JavaScript date to a particular time zone. The default time zone is UTC.


2 Answers

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

like image 149
Grokify Avatar answered Sep 20 '22 11:09

Grokify


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
like image 36
Valentin Montmirail Avatar answered Sep 17 '22 11:09

Valentin Montmirail