0

I am new to nodeJs and using moment.js in my projects. I would like to calculate datetime difference resulting into hours minutes and seconds. I googled but did not got related solution.

Here is the code and my effort on google.

var moment = require('moment');

var now  = "26/02/2014 10:31:30";
var then = "25/02/2014 10:20:30";

var config = "DD/MM/YYYY HH:mm:ss";

var duration = moment.utc(moment(now, config).diff(moment(then,config))).format("HH:mm:ss");

console.log(duration);

This prints 00:11:00 expected result is 23:11:00

any help would be appreciated and thanks in advance.

Denis Tsoi
  • 9,428
  • 8
  • 37
  • 56
user3446467
  • 95
  • 1
  • 13
  • The Problem I'm having is that the format for `now` and `then` are not formatted properly to the latest version of momentjs. I believe you're trying to calculate backwards (from now to the past). However, the moment will return the time difference between `then` and `now` - which equates to `24:11:00` – Denis Tsoi Dec 15 '15 at 08:08

2 Answers2

1

You will have to add:

var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

Output: 24:11:00

Since your time difference is greater than 24 hours, it is resetting to zero. And from there it's giving you the remaining 11:00 mins. Hence the output 00:11:00.

var moment = require('moment');

var now  = "26/02/2014 10:31:30";
var then = "25/02/2014 10:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

console.log(s); 
riser101
  • 610
  • 6
  • 23
1

As referenced in the link below and in my comment, your format will zero into 00:11:00 format above 24 hours.

https://stackoverflow.com/a/18624295/2903169

Now I've just checked this and have provided a snippet from that answer below.

var moment = require('moment');

var now  = "26/02/2014 10:31:30";
var then = "25/02/2014 10:20:30";

var config = "DD/MM/YYYY HH:mm:ss";
var ms = moment(now, config).diff(moment(then,config));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

console.log(s) // will log "24:11:00"

Props to Matt Johnson for providing the answer

Community
  • 1
  • 1
Denis Tsoi
  • 9,428
  • 8
  • 37
  • 56