最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert iso-8601 duration to seconds using moment? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Apr 26, 2015 at 14:11 Angular noobAngular noob 4375 silver badges11 bronze badges 1
  • 1 momentjs is huge. If you are only converting the value, use this instead: npmjs./package/iso8601-duration – Jonathan Commented Mar 23, 2018 at 18:19
Add a ment  | 

1 Answer 1

Reset to default 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
发布评论

评论列表(0)

  1. 暂无评论