27

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?

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
  • 4
    What do you mean by convert to seconds? Show only the seconds part, or convert to total seconds since some starting period? – Nate Barbettini Apr 20 '15 at 10:41
  • 1
    I want to convert the all parts – Ramesh Rajendran Apr 20 '15 at 10:42
  • 3
    Convert to what? You can't convert a single time to seconds. You need a start point and end point (a range) to be able to convert to seconds. E.g. unix time converts whatever date/time you have to seconds since Jan 1 1970. – evolutionxbox Apr 20 '15 at 10:43
  • Do you want 12 hours, 10 minutes and 12 seconds as seconds? You mean would desired result be 43200 seconds + 600 seconds + 12 seconds = 43812 seconds? – makallio85 Apr 20 '15 at 10:46
  • You can do it using JavaScript's getTime function see here http://stackoverflow.com/questions/3830244/get-current-date-time-in-seconds – Martin Apr 20 '15 at 10:47

3 Answers3

49

Try something like this:

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

returns 43812

Travis Collins
  • 3,982
  • 3
  • 31
  • 44
  • 6
    Which version are you using to do this? As if moment.js 2.16.0 it does not accept a string format like you've suggested - http://momentjs.com/docs/#/durations/creating/ – Mike Mellor Nov 17 '16 at 13:08
  • 1
    Answer has been updated according to moment.js 2.1.0 – Joao Aug 07 '17 at 15:00
  • @Joao The answer does not work. Are you saying it only works on 2.1.0? – daveycroqet Oct 31 '17 at 04:27
  • 1
    @daveycroqet Answer has been updated to work in the current version of moment.js, which is 2.19.1 – Travis Collins Oct 31 '17 at 12:20
  • 2
    @TravisCollins It might have been a better idea to leave the original accepted answer with the version it related to, then adding the new answer too with version number, not everyone can up their version easily if they have legacy code etc – StudioTime Oct 31 '17 at 13:09
42

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()
pkerckhove
  • 763
  • 2
  • 10
  • 17
4

For mm:ss to seconds

myVar = moment.duration(`00:${'02:00'}`).asSeconds()//mm:ss to seconds
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
Ajmal Hasan
  • 885
  • 11
  • 9