gpt4 book ai didi

timezone - Moment JS 时区 - 有没有办法检查时间是否早于特定时间?

转载 作者:行者123 更新时间:2023-12-04 14:24:28 25 4
gpt4 key购买 nike

我需要一些功能,我需要使用 momentjs 检查我机器上的本地时间是否在特定时区的上午 9 点之前,假设所有导入工作正常,等等。

因此,例如,如果我的本地时间是纽约上午 11 点,我想检查加利福尼亚时间是否早于上午 9 点。

这是我到目前为止一直在尝试的代码。有更好的方法吗?

if(moment().isBefore(moment(`${moment(new Date()).format("YYYY-MM-DD")} 09:00:00`).tz('America/Los_Angeles'), 'second')) {
console.log('it is before!');
}

最佳答案

请注意

moment(`${moment(new Date()).format("YYYY-MM-DD")} 09:00:00`).tz('America/Los_Angeles')

不代表加利福尼亚州的 9:00 AM ('America/Los_Angeles'),而是今天在您本地时区的 9:00 AM 转换为 'America/Los_Angeles' 时区。

在您的情况下,您可以使用 moment.tz()而不是 tz()功能。

The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.

// Compare current time with today at 9:00 am in Los Angeles
if(moment().isBefore(moment.tz('09:00:00', 'HH:mm:ss', 'America/Los_Angeles'), 'second')) {
console.log('it is before!');
}

// Compare today at 11:00 am in New York with today at 9:00 am in Los Angeles
let mNewYork = moment.tz('11:00:00', 'HH:mm:ss', 'America/Los_Angeles');
let mCalifornia = moment.tz('09:00:00', 'HH:mm:ss', 'America/Los_Angeles')
if(mNewYork.isBefore(mCalifornia, 'second')) {
console.log('it is before!');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data-2012-2022.min.js"></script>

我只是使用 '09:00:00' 字符串得到今天上午 9:00,因为,by default :

You can create a moment object specifying only some of the units, and the rest will be defaulted to the current day, month or year, or 0 for hours, minutes, seconds and milliseconds.

关于timezone - Moment JS 时区 - 有没有办法检查时间是否早于特定时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com