【问题标题】:MomentJS: Compare time in different timezonesMomentJS:比较不同时区的时间
【发布时间】:2014-12-26 19:59:17
【问题描述】:

我有一系列时区,我想知道哪个时区是“最早的”,而最早的时区是最早的时区。

例如:

  • 时区 X 是星期四下午 5 点
  • 时区 Y 是星期四晚上 7 点

比X是其中最早的。

我在 NodeJS 中使用 momentjsmomentjs-timzone(不是浏览器包)

我正在尝试比较毫秒时间戳,但这给了我相同的值:

if (momenttz().tz(timezoneX).format('x') > momenttz().tz(timezoneY).format('x'))

【问题讨论】:

    标签: node.js momentjs


    【解决方案1】:

    在 NodeJS 语法中,它可以通过将时区格式化为偏移值、找到最小组件并返回其时区值来完成:

    var moment = require('moment-timezone');
    
    var inputTzArray = ['Pacific/Chatham', 'America/St_Johns', 'Asia/Jerusalem', 'America/New_York', 'America/Los_Angeles'];
    var tzOffsets = []
    for (var i in inputTzArray) {
       var s = moment.tz(inputTzArray[i]).format('Z'); //format to offset
       tzOffsets[i] = parseFloat(s.replace(':','.')); //parse int offset
    }
    console.log(tzOffsets);
    var minIndex = tzOffsets.indexOf(Math.min.apply(Math, tzOffsets)); //find minimum's index
    
    console.log(inputTzArray[minIndex]); //Output earliest timezone
    

    在链接中的交互式控制台中运行“node server.js”的现场演示:http://runnable.com/VJ3M3XdZAVg-EVOP

    【讨论】:

      猜你喜欢
      • 2017-01-02
      • 2018-03-08
      • 1970-01-01
      • 2012-11-22
      • 2014-10-28
      • 2017-12-18
      • 1970-01-01
      • 2019-05-20
      • 2014-10-31
      相关资源
      最近更新 更多