How to convert HH:MM:SS times to seconds with moment.js?

Sometimes, we want to convert HH:MM:SS times to seconds with moment.js.

In this article, we’ll look at how to convert HH:MM:SS times to seconds with moment.js.

How to convert HH:MM:SS times to seconds with moment.js?

To convert HH:MM:SS times to seconds with moment.js, we can use the diff and startOf methods.

For instance, we write:

const s = moment('12:10:12: PM', 'HH:mm:ss: A').diff(moment().startOf('day'), 'seconds');
console.log(s)

We create a moment object with moment by parsing the time string.

Then we call diff to find the difference between the start of the day and the given time and return the result in seconds.

Therefore s is 43812.

Conclusion

To convert HH:MM:SS times to seconds with moment.js, we can use the diff and startOf methods.