英文:
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 "Europe/London", no matter the user's own time zone.
It only needs to work in modern browsers, and it's fine if the user's browser doesn't happen to handle this time zone – it's for a bit of progressive enhancement where I'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 = "Europe/London"
const dateTimeFormat = new Intl.DateTimeFormat("en-GB", { timeZone, hour: "numeric" })
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("en-GB", { timeZone: "Europe/London", hour: "numeric" });
console.log(hour)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论