在JavaScript中,有没有一种方法可以在不使用toLocaleString的情况下将Date转换为时区? [英] In JavaScript, is there a way to convert a Date to a timezone without using toLocaleString?

查看:63
本文介绍了在JavaScript中,有没有一种方法可以在不使用toLocaleString的情况下将Date转换为时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 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"

那太好了;这段代码告诉我现在几点钟在纽约,但只有 string 格式。如果我想基于小时进行编程操作,则必须解析该字符串。

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

在JavaScript中可能吗?

Is that possible in JavaScript?

推荐答案

不幸的是,不-使用 Date 对象是不可能的。

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

您可以使用诸如 Luxon 之类的库来执行此操作,但是在内部它确实在处理 toLocaleString 完成此操作。

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

ECMAScript临时提案正在努力改善此类情况。

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

这篇关于在JavaScript中,有没有一种方法可以在不使用toLocaleString的情况下将Date转换为时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆