Philipp Meissner
Philipp Meissner

Reputation: 5482

Calculate duration between momentjs timestamps in UTC

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?

Upvotes: 0

Views: 2490

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

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.

Upvotes: 3

Related Questions