我需要一些功能,在这些功能中,我需要使用MomentSjs(假设所有导入工作正常工作,等等(,我需要检查我的计算机上的本地时间是否在9点之前的当地时间。P>
所以,例如,如果我的当地时间是纽约上午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在加利福尼亚州('America/Los_Angeles'
(,但今天在您的本地时区中的9:00 AM转换为'America/Los_Angeles'
TimeZone。
在您的情况下,您可以使用moment.tz()
而不是tz()
函数。
moment.tz
构造函数采用与moment
构造器相同的参数,但将最后一个参数用作时区标识符。
// 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获取,因为,默认情况下:
您可以创建一个只指定某些单元的时刻对象,其余的将默认为当天,月或年,或0小时,分钟,秒和毫秒。