【问题标题】:Getting a time difference across timezones with moment-timezone使用时刻时区获得跨时区的时差
【发布时间】:2018-10-04 20:33:38
【问题描述】:

我得到一个代表时间的字符串和一个时区 ID。我需要确定有问题的时间是否发生在接下来的半小时内,但我正在运行的计算机与捕获字符串的时区不同。小注:如果事件发生在过去,没关系(仍然发生 === true)。只是试图将未来半小时以上发生的事情与其他事情区分开来。

这似乎应该是直截了当的,但我却一无所获。

const moment = require('moment-timezone')

const hm = s => moment(s).format('HH:mm')

const happensSoon = (then, timezoneId) => {
  console.log(`then:`, then)             // 2018-10-04T16:39:52-07:00
  console.log(`timezoneId:`, timezoneId) // America/New_York
  const localNow = moment()
    .clone()
    .tz(timezoneId)
  const localThen = moment(then)
    .clone()
    .tz(timezoneId)
  const diff = localThen.diff(localNow, 'minutes')
  console.log(`localThen:`, hm(localThen)) // 19:39
  console.log(`localNow:`, hm(localNow))   // 16:24
  console.log(`then:`, hm(then))           // 16:39
  console.log(`diff:`, diff)               // 194
  return diff <= 30
}

在“美国/洛杉矶”时区运行。我的“本地”是为了代表纽约时间。所以,16:39 是then 的输入值,我希望比较大约在那个时间(哦,我在开发人员本地时间大约 13:20 运行它)。所以,基本上,在上面的代码中,我想比较 16:39 和 16:20,大苹果到大苹果。我不想闯入这个;我想要一个我理解的解决方案。谢谢!

【问题讨论】:

    标签: momentjs moment-timezone


    【解决方案1】:

    这对我有用:

    const happensSoon = (then, timezoneId) => {
      const thenThere = moment.tz(then, timezoneId)
      const nowThere = moment().tz(timezoneId)
      const diff = thenThere.diff(nowThere, 'minutes')
      return diff <= 30
    }
    

    给定一个没有时区信息的时间字符串then 和一个timezoneId,它会在该时间和时区创建一个时刻,然后创建一个新时刻并将其转换为相同的时区,然后区分它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 2023-04-01
      • 2016-08-24
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多