Ken Kinder
Ken Kinder

Reputation: 13140

In JavaScript, is there a way to convert a Date to a timezone without using toLocaleString?

I've found that toLocaleString can be effective in translating the time to a different timezone, as discussed on this question already. For example, to print the time in New York:

console.log(new Date().toLocaleString("en-US", {timeZone: "America/New_York"}))
"5/26/2020, 1:27:13 PM"

That's great; this code gives me what time it is in New York, but only in string format. If I want to do something programmatic based on the hours, I'll have to parse that string.

Is there a way I can generate a date object with a specific timezone, without coercing it into a string? For example, I want this imaginary function:

const newYork = new Date().toTimezone('America/New_York')
console.log(newYork.getHours(), newYork.getMinutes())
13 27     // <--- 13:27 (1:27pm) in New York, not the browser's timezone

Is that possible in JavaScript?

Upvotes: 2

Views: 57

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241485

Unfortunately, no - that's not possible with the Date object.

You can use a library such as Luxon to do this, but internally it is indeed manipulating the string result of toLocaleString to accomplish this.

const newYork = luxon.DateTime.local().setZone('America/New_York');
console.log(newYork.hour, newYork.minute); // just an example, like in your question

The ECMAScript Temporal proposal is working to improve such things in the future.

Upvotes: 4

Related Questions