Moment.js moment.duration().milliseconds()方法
moment().duration().milliseconds()方法用于获取持续时间的毫秒数。这个毫秒数是作为秒的子集计算的,因此它的值介于0和999之间。一秒的长度为1000毫秒。
语法:
moment().duration().milliseconds();
参数: 此方法不接受任何参数。
返回值: 此方法返回持续时间的毫秒数(0-999)。
注意: 此方法在普通的Node.js程序中不起作用,因为它需要全局安装或在项目目录中安装moment.js库。
可以使用以下命令安装Moment.js:
安装moment模块:
npm install moment
下面的示例将展示Moment.js的moment.duration().milliseconds()方法。
示例1:
const moment = require('moment');
let durationOne =
moment.duration(900, 'milliseconds');
let durationTwo =
moment.duration(5750, 'milliseconds');
// This returns 900 as the number of
// milliseconds is less than a whole second
console.log(
"durationOne milliseconds is:",
durationOne.milliseconds()
)
// This returns 750 as the number of milliseconds
// is greater than 5 seconds, and therefore
// returns the value of milliseconds
// of the next second (next 750 milliseconds)
console.log(
"durationTwo milliseconds is:",
durationTwo.milliseconds()
)
输出:
durationOne milliseconds is: 900
durationTwo milliseconds is: 750
示例2: 这个示例将帮助理解这个方法与asMilliseconds()方法之间的差异,以便更好地理解。
const moment = require('moment');
let durationA =
moment.duration(1, 'seconds');
let durationB =
moment.duration({ seconds: 5, milliseconds: 250 });
// The asMilliseconds() method will return the
// length of the duration in milliseconds
console.log(
"Length of durationA in milliseconds is:",
durationA.asMilliseconds()
)
console.log(
"durationA milliseconds is:",
durationA.milliseconds()
)
console.log(
"Length of durationB in milliseconds is:",
durationB.asMilliseconds()
)
console.log(
"durationB milliseconds is:",
durationB.milliseconds()
)
输出:
Length of durationA in milliseconds is: 1000
durationA milliseconds is: 0
Length of durationB in milliseconds is: 5250
durationB milliseconds is: 250
参考资料: https://momentjs.com/docs/#/durations/milliseconds/