Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert iso-8601 duration to seconds using moment?

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.

like image 774
Angular noob Avatar asked Apr 26 '15 14:04

Angular noob


People also ask

How do I specify the duration in an ISO 8601 format?

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.

Does ISO 8601 support milliseconds?

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).

How do I convert ISO date to long date?

date = new Date('2013-03-10T02:00:00Z'); date. getFullYear()+'-' + (date. getMonth()+1) + '-'+date. getDate();//prints expected format.


1 Answers

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
like image 84
victorkt Avatar answered Sep 21 '22 16:09

victorkt