TheBigDoubleA
TheBigDoubleA

Reputation: 452

How to force correct timezone for Javascript New Date()?

I'm trying to get the current midnight date with Javascript and I use this:

var mydate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), 0, 0, 0, 0);

I receive this:

Sun Oct 26 2014 00:00:00 GMT+0100 (BST)

The problem is, that it's not British Summer Time anymore, but for some reason javascript still thinks it is. This is messing up my entire application, as I convert this into a timestamp like this:

mydate = Math.round(to_day.getTime() / 1000);

How can I change this?

Upvotes: 2

Views: 4682

Answers (1)

Lix
Lix

Reputation: 47976

JavaScript will always use your computer's locale to extract the date. It's using BST because this is the timezone that you have set (automatically perhaps?).

You can extract a UTC time string by calling the following function:

var d = new Date();
d.toUTCString(); // "Sun, 26 Oct 2014 11:46:11 GMT"

There are libraries that deal specifically with manipulation of date objects. One such tool I recommend you checkout is moment.js. It gives you the option to convert between timezones as well as a whole lot of other useful time/date related features.

Upvotes: 1

Related Questions