计算UTC中moment.js时间戳之间的持续时间 [英] Calculate duration between momentjs timestamps in UTC

查看:497
本文介绍了计算UTC中moment.js时间戳之间的持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难计算两个时间戳的持续时间(时间差). 我从服务器收到的时间戳格式如下:

I am having a hard time to calculate the duration (difference in time) of two timestamps. There is a timestamp I receive from the server in the following format:

start # => "2017-05-31 06:30:10 UTC" (这基本上是红宝石DateTime.now.utc)

start # => "2017-05-31 06:30:10 UTC" (This is basically rubys DateTime.now.utc)

我想看看从那时到现在为止已经过去了几个小时. 计算仅在angularjs前端进行. 我尝试了以下方法:

I want to see how many hours have passed since then until as of right now. The calculation happens in the angularjs frontend only. I tried the following:

var start = moment("2017-05-31 06:30:10 UTC", "YYYY-MM-DD HH:mm:ss Z").utc();
var now = moment.utc();
var duration = moment.duration(now.diff(start));
console.log(duration.asHours()); #=> 2 hours even though the point in time was just a couple of minutes ago.

不幸的是,这将始终使用我的设备的本地时间,并且所产生的时间比实际时间少几个小时.

Unfortunately this would always use my devices local time and produce a time that's a few hours off the actual time.

所以我的方法是将所有时间都转换为UTC,然后让momentjs处理所有这些事情.

So my approach was to either convert all times to UTC and let momentjs handle all this.

我想念什么?

推荐答案

由于您输入的是UTC,因此您可以使用

Since your input is UTC you can use moment.utc method.

默认情况下,时刻会解析并以当地时间显示.

By default, moment parses and displays in local time.

如果要解析或显示UTC时间,可以使用moment.utc()代替moment().

If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().

这里有个例子:

var start = moment.utc("2017-05-31 06:30:10 UTC", "YYYY-MM-DD HH:mm:ss Z");
var now = moment.utc();
var duration = moment.duration(now.diff(start));
console.log(duration.asHours());

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

在代码示例中,您将输入字符串解析为本地日期,然后将其转换为UTC(使用

In your code sample, you are parsing the input string as local date and then converting it to UTC (with utc() method).

请参阅本地vs UTC vs偏移量指南以获取更多信息信息.

See Local vs UTC vs Offset guide to get more info.

这篇关于计算UTC中moment.js时间戳之间的持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆