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

僤鯓⒐⒋嵵緔 提交于 2020-05-30 03:52:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/62028050/in-javascript-is-there-a-way-to-convert-a-date-to-a-timezone-without-using-tolo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!