Tirthankar Kundu Tirthankar Kundu - 8 months ago 51
Node.js Question

Difference between two times in format (hh: mm: ss)

I have two times, let say:

t1= '05:34:01' ;
t2= '20:44:44' ;

I want two evaluate difference between these two times in same format. Like the result of above must come as

t3= t2 - t1; // 15:10:43

What is the way to do it?


Highly recommend you include moment.js in your project if you need to handle time.


var t1 = moment('05:34:01', "hh:mm:ss");
var t2 = moment('20:44:44', "hh:mm:ss");
var t3 = moment(t2.diff(t1)).format("hh:mm:ss");

Working jsFiddle

To install moment.js in Node.js, simply do:

npm install moment (or for a global install sudo npm -g install moment)

And then in your Node.js, include it like so:

var moment = require('moment');

Edit: For 24h clock, change hh to HH.