I am given a string representing a time, and a timezone ID. I need to determine whether the time in question occurs within the next half hour, but the computer I'm running on is in a different timezone than the one where the string was captured. Minor note: it's OK (still happensSoon === true) if the event happened in the past). Just trying to distinguish things which happen more than a half hour in the future from the rest.
This seems like it ought to be straightforward, but I'm getting nowhere with it.
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
}
Running in "America/Los_Angeles" timezone. My "local" is intended to represent the New York time. So, 16:39 is the input value for then
and I expect the comparison to be around that time (Oh, I'm running this at about 13:20 developer-local time). So, basically, in the code above, I want to be comparing 16:39 with 16:20, big-apples-to-big-apples. I don't want to hack my way into this; I want a solution I understand. Thanks!
This does the job for me:
const happensSoon = (then, timezoneId) => {
const thenThere = moment.tz(then, timezoneId)
const nowThere = moment().tz(timezoneId)
const diff = thenThere.diff(nowThere, 'minutes')
return diff <= 30
}
Given a time string then
without timezone information and a timezoneId
, it creates a moment at that time and timezone, then creates a new moment and translates it to the same timezone, then diffs them.