简体   繁体   中英

Find time difference between 2 times using moment.js

I have a requirement to find the difference between 2 times(times in HH:MM:SS) format.

Need to get the difference in seconds.

var a = moment('21:04:59');
var b = moment('21:04:00');

a - b = 59 seconds 

I have tried following Its worked for me with date time format, but not time filed alone.

var a = moment('2016-06-06T20:30:59');
var b = moment('2016-06-06T20:30:00');

console.log(a.diff(b, 'seconds')) // 59 seconds

you have to pass time like following in moment

var a = moment({
  h: 21,
  m: 04,
  s: 59
});
var b = moment({
  h: 21,
  m: 04,
  s: 00
});

OUTPUT
console.log(a.diff(b, 'seconds')) // 59 seconds

In core, moment.js doesn't have support for time-only data. Even if you provide time-only data, it will try to store "today" as date.

But still you can do that.

Legal Way

var a = moment('21:04:59', 'HH::mm::ss');
var b = moment('21:04:50', 'HH::mm::ss');

alert(a-b); // returns miliseconds

Tricky Alternative

var dummyDate = '2016-05-05T'; // any date
var a = moment(dummyDate + '21:04:59');
var b = moment(dummyDate + '21:04:00');
console.log(a.diff(b, 'seconds'))

You simply have to add the right format ( 'HH:mm:ss' ) when parsing your string into moment object.

Your code gives a Deprecation warning because you are trying to parse a string that is not in a known ISO 8601 format. As the documentation states :

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

Note that, since you are not providing info about the day part, moment creates an object with the current date, month, and year.

Here a working example:

 var a = moment('21:04:59', 'HH:mm:ss'); var b = moment('21:04:00', 'HH:mm:ss'); console.log(a.diff(b, 'seconds')); 
 <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> 

Funny thing: I gave you a similar answer a little time ago

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM