1

I'm writing a service in node js. I have used moment js for time related solutions. I want to calculate the time difference between two times. Here is my snippet and it's not giving me the desired output :

var now = moment('11:08:30',"H:mm:ss");
var prev = moment('11:07:30', "H:mm:ss");
var result = moment(now.diff(prev)).format("H:mm:ss");
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>

As per my understanding, I think the difference between 11:08:30 and 11:07:30 should come out as 00:01:00 but instead the output is coming as 5:31:00. I don't understand why this is happening. How do I fix it so that the output is 00:01:00 i.e 1 minute ?

node_man
  • 1,359
  • 4
  • 23
  • 50
  • `now.diff(prev)` returns the difference in milliseconds, in your case `60000`. With `moment(60000)` you create a date `60000` milliseconds since 1 January 1970 UTC. If you now call `.format("H:mm:ss")` then `H` would be influenced by the timezone of your system. So you need to ensure that you work with utc while formatting. – t.niese Nov 29 '18 at 06:36
  • 2
    So just change `moment(now.diff(prev)).format("H:mm:ss")` to `moment.utc(now.diff(prev)).format("H:mm:ss")`as described in this [answer](https://stackoverflow.com/a/29747198/1960455) and you have the output `0:01:00` – t.niese Nov 29 '18 at 06:43
  • hey thank you soo much this really solved the problem :) – node_man Nov 29 '18 at 06:45

1 Answers1

1

This is a working example,

var now = moment('11:08:30',"H:mm:ss");
var prev = moment('11:07:30', "H:mm:ss");

 function dateDifference(startDate, endDate){
        return moment(startDate).diff(moment(endDate), 'seconds');
    }
    console.log(this.dateDifference(now,prev))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>

The supported measurements are years, months, weeks, days, hours, minutes, and seconds. For ease of development, the singular forms are supported as of 2.0.0. Units of measurement other than milliseconds are available in version 1.1.1.


Now, once u get answer in seconds, then please follow this link to convert seconds into your desired format 'h:mm:ss'

format seconds into 'hh:mm:ss'

siddharth shah
  • 1,139
  • 1
  • 9
  • 17