获取特定时区当前小时的简单方法在现代JavaScript中是什么?

huangapple go评论65阅读模式
英文:

Simple way of getting current hour in a specfic time zone in modern JavaScript?

问题

以下是已翻译的内容:

我想要获取时区为“Europe/London”的当前小时(例如,如果时间是13:45,则获取`13`),无论用户的时区如何。

它只需要在现代浏览器中运行,如果用户的浏览器不支持此时区,那也没关系 - 这只是一种渐进式增强,如果失败,我可以包裹在`try`/`catch`中并不执行任何操作。

以下是我能想到的最佳方法。

```javascript
const timeZone = "Europe/London"
const dateTimeFormat = new Intl.DateTimeFormat("en-GB", { timeZone, hour: "numeric" })
const hour = parseInt(dateTimeFormat.formatToParts(new Date)[0].value, 10)

是否有更简单的方法?


<details>
<summary>英文:</summary>

I want to get the current hour (e.g. `13` if the time is 13:45) in the time zone &quot;Europe/London&quot;, no matter the user&#39;s own time zone.

It only needs to work in modern browsers, and it&#39;s fine if the user&#39;s browser doesn&#39;t happen to handle this time zone – it&#39;s for a bit of progressive enhancement where I&#39;m fine wrapping it in a `try`/`catch` and doing nothing if it fails.

The following was the best I could come up with.

``` javascript
const timeZone = &quot;Europe/London&quot;
const dateTimeFormat = new Intl.DateTimeFormat(&quot;en-GB&quot;, { timeZone, hour: &quot;numeric&quot; })
const hour = parseInt(dateTimeFormat.formatToParts(new Date)[0].value, 10)

Is there a simpler way?

答案1

得分: 1

你可以使用toLocaleString()方法。

const hour = new Date().toLocaleString("en-GB", { timeZone: "Europe/London", hour: "numeric" });
console.log(hour);
英文:

You can use toLocaleString() method

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const hour = new Date().toLocaleString(&quot;en-GB&quot;, { timeZone: &quot;Europe/London&quot;, hour: &quot;numeric&quot; });

console.log(hour)

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月18日 18:11:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定