简体   繁体   English

如何在moment.js中比较不同时区的日期

[英]How to compare dates with different timezones in moment.js

My server's date format is in UTC . 我的服务器的日期格式是UTC I am running my node server in UTC format. 我正在以UTC格式运行我的节点服务器。 I wanna check whether the current time is greater than 8AM in Indian timezone ie +5.30 and should send a mail. 我想检查当前时间是否大于Indian timezone上午8点,即+5.30并且应该发送邮件。 How can I identify this using moment.js 我如何使用moment.js识别这个

Using moment-timezone : 使用时刻时区

if (moment.tz("08:00","HH:mm","Asia/Kolkata").isBefore()) {
  // ...
}

Or, since India does not use daylight saving time, you actually don't need moment-timezone. 或者,由于印度不使用夏令时,实际上你不需要时刻时区。 You just need to specify the fixed offset correctly. 您只需要正确指定固定偏移量即可。 Other zones that use DST or have other base-offset transitions to consider will indeed need moment-timezone. 其他使用DST或具有其他基本偏移转换的区域确实需要时刻 - 时区。

if (moment.parseZone("08:00+05:30","HH:mmZ").isBefore()) {
  // ...
}

With both of the above, keep in mind that isBefore will default to the current time when there are no parameters. 对于上述两种情况,请记住,当没有参数时, isBefore将默认为当前时间。 You could write it using moment().isAfter(...) , instead, but it's slightly shorter the other way. 您可以使用moment().isAfter(...)来编写它,相反,它会稍微缩短另一种方式。

It doesn't matter whether you compare against UTC or local time because internally moment is tracking the instantaneous UTC-based value anyway. 无论您是将UTC还是本地时间进行比较都无关紧要,因为内部时刻无论如何都会跟踪基于UTC的瞬时值。

You can use isAfter and Moment Timezone : 你可以使用isAfterMoment Timezone

// Get server date with moment, in the example serverTime = current UTC time
var serverDate = moment.utc();
// Get time in India with Moment Timezone
var indiaDate = moment.tz("Asia/Kolkata");
// Setting time to 8:00 AM (I'm supposing you need to compare with the current day)
indiaDate.hours(8).minutes(0).seconds(0);
if( serverDate.isAfter(indiaDate) ){
    // Server date is greater than 8 AM in India
    // Add here the code to send a mail
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM