David Torres
David Torres

Reputation: 1767

How to transform a JavaScript Date to a different timezone

If I run var myDate = new Date('29-06-2016 10:00'), myDate will only contain one thing: a number. The number of milliseconds from 01-01-1970 00:00:00 GMT to 29-06-2016 10:00:00 XXX

XXX being the timezone of the OS. In my case BST (because it is a summer date, in winter would be GMT).

Now... What if I want the milliseconds from 01-01-1970... to 29-06-2016 10:00:00 GMT-7?

I only found methods to tell me what time is in the GMT-7 timezone when in BST timezone is 29-06-2016 10:00:00, but that is not what I am looking for!

Also, to change an environmental variable so the timezone is GMT-7 is not an option.

Upvotes: 0

Views: 943

Answers (2)

David Torres
David Torres

Reputation: 1767

I think I found a way of doing it, using moment.js as ErikS suggested:

// This code is running in a Node.js server configured to use UTC

// Incorrect date, as it is interpret as UTC.
// However, we do this to get the utcOffset
var auxDate = moment.tz(new Date('2016-6-23 10:15:0'), 'US/Mountain');

// Get the milliseconds since 1970 of the date as if it were interpreted 
// as GMT-7 or GMT-6 (depends on the date because of Daylight Saving Time)
var milliseconds = auxDate.valueOf() - auxDate.utcOffset() * 60000;

Upvotes: 0

Robin French
Robin French

Reputation: 715

I think you want the date string in the following format

"2016-06-29T10:00:00-07:00"

That lets you set the timezone relative GMT (not 100% sure on the timezone, but it's client side so does depend on their locale).

I had a similar thing where JS was changing the time on date objects and the only way I found was to set up the date and set this.

Bonus info, to get this from a .NET DateTime using the following string format.

"yyyy-MM-ddTHH:mm:sszzz"

Upvotes: 2

Related Questions