Evan P.
Evan P.

Reputation: 989

How can I get the UTC value of a date and time in a time zone in Javascript?

I'd like to be able to create a Date object with a time like "Midnight in Los Angeles on Christmas 2011".

I've used moment.js, which is great, and moment-timezone, which is even better, but neither the default Date class nor the moment constructors take a timezone as an argument.

I've been able to fudge it by using a formatted RFC2822 string, like so:

 d = new Date("12-25-2011 PST")

...but it requires that I know that December 25 is standard time. This gives a different answer:

d = new Date("12-25-2011 PDT")

Ideally I'd like to use geographical-style timezones like "America/Los_Angeles".

Upvotes: 2

Views: 528

Answers (2)

Evan P.
Evan P.

Reputation: 989

OK, I think I know how to do this. I'm using the great timezone package from npm. Here's the rough idea:

var tz = require("timezone");

var dateInZone = function(dt, zone) {
    return new Date(tz(dt, zone, require("timezone/"+zone), "%FT%T%^z"));
};

console.log(dateInZone([2011, 12, 25], "America/Los_Angeles"));

Upvotes: 1

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241818

See moment-timezone #11 and #25.

If you get the latest develop from GitHub sources, you can do this:

moment.tz('2011-12-25T00:00:00','America/Los_Angeles').utc().format()

The only reason it hasn't been released yet is because we're still deciding what to do about ambiguous or invalid input, per #27.

Upvotes: 1

Related Questions