Convert HH:MM:SS to seconds in momentjs

All we need is an easy explanation of the problem, so here it is.

I have a string with 12 hour formatted time only

var time="12:10:12: PM"

I want to convert this string to seconds.

how can i do this in moment.js?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Try something like this:

moment('12:10:12: PM', 'HH:mm:ss: A').diff(moment().startOf('day'), 'seconds');

returns 43812

Method 2

I was just trying to achieve the same thing. using
https://momentjs.com/

This is how I got what I wanted (03:11:23 => 11483 seconds)

myVar = moment.duration(myVar).asSeconds()

Method 3

For mm:ss to seconds

myVar = moment.duration(`00:${'02:00'}`).asSeconds()//mm:ss to seconds

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply