使用 moment-timezone 获取跨时区的时差

Getting a time difference across timezones with moment-timezone

我得到一个代表时间的字符串和一个时区 ID。我需要确定所讨论的时间是否在接下来的半小时内发生,但我 运行 使用的计算机与捕获字符串的计算机处于不同的时区。小注:如果事件发生在过去,那没关系(仍然 happensSoon === 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
}

运行 "America/Los_Angeles" 时区。我的 "local" 旨在代表纽约时间。所以,16:39 是 then 的输入值,我希望比较在那个时间左右(哦,我 运行 这个大约是 13:20 开发者本地时间).所以,基本上,在上面的代码中,我想比较 16:39 和 16:20,大苹果对大苹果。我不想闯入这个领域;我想要一个我理解的解决方案。谢谢!

这对我有用:

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,它在那个时间和时区创建一个时刻,然后创建一个新时刻并将其转换为相同的时区,然后进行差异他们。