6

I have an iso-8601 duration which is as follows:

PT15M51S

I want to convert the duration into seconds so that I can store it in the db and order by duration etc.

Here is what I tried so far:

var moment = require('moment');
var duration = 'PT15M51S';
var x = moment(duration, moment.ISO_8601);
console.log(x.seconds());

Which results in NaN.

Angular noob
  • 437
  • 4
  • 11
  • 1
    momentjs is huge. If you are only converting the value, use this instead: https://www.npmjs.com/package/iso8601-duration – Jonathan Mar 23 '18 at 18:19

1 Answers1

8

You need to use moment.duration function. Also, to get the total value in seconds, use asSeconds() instead of seconds().

In your case:

var moment = require('moment');
var duration = 'PT15M51S';
var x = moment.duration(duration, moment.ISO_8601);
console.log(x.asSeconds()); // => 951
victorkt
  • 13,992
  • 9
  • 52
  • 51
  • Sounds promising. I'll check this out now. – Angular noob Apr 26 '15 at 15:36
  • 1
    error TS2345: Argument of type 'MomentBuiltinFormat' is not assignable to parameter of type 'DurationConstructor'. Type 'MomentBuiltinFormat' is not assignable to type '"Q"'. – Cichy Apr 02 '21 at 08:15