Dibish
Dibish

Reputation: 9293

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

Upvotes: 1

Views: 5209

Answers (3)

Tuğca Eker
Tuğca Eker

Reputation: 1493

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'))

Upvotes: 1

VincenzoC
VincenzoC

Reputation: 31482

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

Upvotes: 0

Pranav Patel
Pranav Patel

Reputation: 1559

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

Upvotes: 2

Related Questions