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

6

我的服务器日期格式是 UTC。我正在使用 UTC 格式运行我的节点服务器。我想要检查当前时间是否在印度时区(即 +5.30)的早上 8 点之后,并发送一封邮件。如何使用 moment.js 来实现这个功能。


2
此功能已拆分为moment-timezone。您可以在此处找到文档http://momentjs.com/timezone/。 - Tom A
2个回答

9

使用moment-timezone

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

或者,由于印度不使用夏令时,您实际上不需要moment-timezone。您只需要正确指定固定偏移量即可。其他使用DST或有其他基本偏移量转换要考虑的区域确实需要moment-timezone。

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

需要记住的是,当没有参数时isBefore会默认为当前时间。你可以使用moment().isAfter(...)来编写它,但以另一种方式编写稍微短一些。

无论您比较UTC还是本地时间,都没有关系,因为内部 moment 正在跟踪瞬时基于 UTC 的值。


2

您可以使用isAfterMoment时区

// 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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接