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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.