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
.
Briefly, the ISO 8601 notation consists of a P character, followed by years, months, weeks, and days, followed by a T character, followed by hours, minutes, and seconds with a decimal part, each with a single-letter suffix that indicates the unit. Any zero components may be omitted.
ISO 8601 FormatsISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).
date = new Date('2013-03-10T02:00:00Z'); date. getFullYear()+'-' + (date. getMonth()+1) + '-'+date. getDate();//prints expected format.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With