简体   繁体   English

使用moment.js比较来自不同时区的时间

[英]Comparing time from different timezones with moment.js

I have a Node.js server that triggers function based on timezones. 我有一台基于时区触发功能的Node.js服务器。 Specifically, I'm using moment-timezone and from a fixed date and time input I need to trigger action at that same input but in different time zones. 具体来说,我使用了矩时区,并且从固定的日期和时间输入中,我需要在相同的输入但在不同的时区中触发动作。

So if I set in my server that the action should be triggered at 1:00 pm UK time and the user is in New York, I want the action to be triggered at 1:00 pm in New York. 因此,如果我在服务器中设置该操作应在英国时间下午1:00触发,并且用户在纽约,则希望该操作在纽约时间下午1:00触发。

That's what I am doing now: 那就是我现在正在做的:

exports.time_to_trigger = function(hour, date) {
    var user_timezone = "Asia/Tokyo";

    // create date object from date + hour strings
    var dateObj = moment(date + hour, process.env.DATE_FORMAT + " HH:mm a");

    // create offset
    var max_value = moment(dateObj).add(3, 'minutes');
    var low_value = moment(dateObj).add(-3, 'minutes');

    console.log(max_value); // -> moment("2018-01-25T13:03:00.000")
    console.log(low_value); // -> moment("2018-01-25T12:57:00.000")

    // get the now value of the user timezone
    var user_now = moment.tz(moment(), user_timezone);

    console.log(user_now); // -> moment.parseZone("2018-01-24T13:01:00.038+09:00")

    console.log(user_now.isAfter(low_value)); // -> false
    console.log(user_now.isBefore(max_value)); // -> true

    return (
        user_now.isAfter(low_value) &&
        user_now.isBefore(max_value)
    )
}

As you can see from the comment, this is not working as the comparison with isAfter and isBefore take into consideration the time zone that I converted on purpose not to have this problem. 从评论中可以看到,这与isAfter和isBefore的比较不起作用,考虑到我故意转换的时区没有此问题。 How can I solve this? 我该如何解决?

Your issue is that you use timezone to get user_now but not to create dateObj . 您的问题是您使用时区来获取user_now而不是创建dateObj So dateObj is missing the timezone offset and your 2 dates are not comparable as you would wish. 因此dateObj缺少时区偏移,因此您想要的2个日期不具有可比性。

To have all your dates on the same timezone: 要使所有日期都在同一时区:

// create date object from date + hour strings
var dateObj = moment.tz(date + hour, process.env.DATE_FORMAT + " HH:mm a", user_timezone);

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

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