momentjs - 使用 moment-timezone 获得跨时区的时差
问题描述
我得到一个代表时间的字符串和一个时区 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,大苹果到大苹果。我不想闯入这个;我想要一个我理解的解决方案。谢谢!
解决方案
这对我有用:
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
给定一个没有时区信息的时间字符串和 a timezoneId
,它会在该时间和时区创建一个时刻,然后创建一个新时刻并将其转换为相同的时区,然后区分它们。
推荐阅读
- c# - 如何使用 .net core 和 C# 在 Sharepoint 中上传文件?
- javascript - 如何让机器人不和谐响应特定的文本频道
- iis - 文件表 (SQL Server 2016) 文件流权限在 IIS 中丢失
- c - 这段代码在 C 中将两个矩阵相乘有什么问题?
- python - 在 django 用户更改表单中更改图像
- visual-studio-code - 虚幻引擎开发使用 vscode 不使用 vs2019, 2017
- dataframe - 将数据框 pyspark 中的列与空值连接起来
- c# - 在 try catch 块中向用户显示 net core web 应用程序中的错误
- bash - 使用 Bash 脚本为循环和 if 测试创建文件
- python-3.x - Discord.py 查看用户是否在语音通话