如何使用moment将iso-8601持续时间转换为秒?

Ang*_*oob 4 javascript iso node.js momentjs

我的iso-8601持续时间如下:

PT15M51S
Run Code Online (Sandbox Code Playgroud)

我想将持续时间转换为秒,以便我可以将其存储在数据库中并按持续时间顺序等.

这是我到目前为止尝试的内容:

var moment = require('moment');
var duration = 'PT15M51S';
var x = moment(duration, moment.ISO_8601);
console.log(x.seconds());
Run Code Online (Sandbox Code Playgroud)

结果如何NaN.

vic*_*ohl 6

你需要使用moment.duration功能.此外,要以秒为单位获取总值,请使用asSeconds()而不是seconds().

在你的情况下:

var moment = require('moment');
var duration = 'PT15M51S';
var x = moment.duration(duration, moment.ISO_8601);
console.log(x.asSeconds()); // => 951
Run Code Online (Sandbox Code Playgroud)