使用时刻和时刻时区正确实现差异

使用时刻和时刻时区正确实现差异

本文介绍了使用时刻和时刻时区正确实现差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 moment 的 diff 函数来计算时间 b/w 中的毫秒差异,一个时刻将始终具有恒定时区和另一个时区无关时刻.我正在使用时刻时区来帮助解决这个问题.

Trying to use moment's diff function to calculate ms difference in time b/w one moment that will always have a constant timezone and another timezone indifferent moment. I'm using moment-timezone to help with this.

这是我的示例代码:

const parisTime   = moment({hour:18, minutes:0}).tz('Europe/Paris');
const currentTime = moment(); //right now
const difference  = moment.duration(parisTime.diff(currentTime))

当我执行此操作时,diff 将 currentTime 视为与 Europe/Paris 相同的时区,这将不起作用 b/c currentTime 可能来自世界任何地方.

When I perform this operation diff treats currentTime as the same timezone as Europe/Paris which won't work b/c currentTime could be from anywhere in the world.

任何想法如何解决这个问题?非常感谢您的帮助 - 正确答案将被标记为如此.

Any ideas how to resolve this ?Your help is much appreciated - correct answer will be marked as so.

谢谢!

推荐答案

我想您想计算今天巴黎时间 18:00 与现在之间的差异.那将是

I think you want to compute the difference between today at 18:00 Paris time and now. That would be

moment.tz('18:00', 'HH:mm', 'Europe/Paris').diff(moment());

基本上,您需要将 18:00 解析为巴黎时间.现在发生的事情是您将其解析为当地时间,然后将其转换为巴黎时间.

Basically, you need to parse 18:00 as Paris time. What is happening right now is that you are parsing it as local time, and then converting that to Paris time.

请注意,由于您没有指定日期,因此假定日期为今天",这意味着此代码可以产生正值和负值.

Note that because you aren't specifying a date, the day is assumed to be 'today', meaning that this code can result in both positive and negative values.

请参阅这篇博文有关 moment 的构造函数如何工作的更多信息.

See this blog post for more information about how moment's constructor functions work.

这篇关于使用时刻和时刻时区正确实现差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 12:36