Calculate duration between momentjs timestamps in UTC

非 Y 不嫁゛ 提交于 2020-01-07 04:24:09

问题


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" (This is basically rubys DateTime.now.utc)

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.

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

What am I missing?


回答1:


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

By default, moment parses and displays in local time.

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

Here a live example:

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>

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

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



来源:https://stackoverflow.com/questions/44277682/calculate-duration-between-momentjs-timestamps-in-utc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!