代码之家  ›  专栏  ›  技术社区  ›  Carl Manaster

使用矩时区获得跨时区的时差

  •  0
  • Carl Manaster  · 技术社区  · 6 年前

    我得到了一个表示时间的字符串和一个时区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

    1 回复  |  直到 6 年前
        1
  •  0
  •   Carl Manaster    6 年前

    这对我来说很有用:

    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

    推荐文章