Moment.js moment.duration().hours() 方法
moment().duration().hours() 方法 用于获取持续时间的小时数。这个小时数是作为一天的子集计算的,因此它的值在0到23之间。
语法:
moment().duration().hours();
参数: 此方法不接受任何参数。
返回值: 此方法返回持续时间的小时数(0-23)。
注意: 这个方法在正常的Node.js程序中无法工作,因为它需要全局或项目目录中安装外部的moment.js库。
可以使用以下命令安装moment.js:
moment模块的安装:
npm install moment
以下示例将展示Moment.js的 moment.duration().hours() 方法。
示例1:
const moment = require('moment');
let durationOne = moment.duration(20, 'hours');
let durationTwo = moment.duration(28, 'hours');
// This returns 20 as the number of
// hours is less than a whole day
console.log(
"durationOne hours is:", durationOne.hours()
)
// This returns 4 as the number of hours
// is greater than a whole day (24 hours),
// and therefore returns the value of hours
// of the next day (next 4 hours)
console.log(
"durationTwo hours is:", durationTwo.hours()
)
输出:
durationOne hours is: 20
durationTwo hours is: 4
示例2: 此示例将帮助您理解此方法与 asHours() 方法之间的区别,以便更好地理解。
let durationA = moment.duration(50, 'hours');
let durationB = moment.duration(64, 'hours');
// The asHours() method will return the
// length of the duration in hours
console.log(
"Length of durationA in hours is:", durationA.asHours()
)
// The hours() method will return the hour of the duration
console.log("durationA hours is:", durationA.hours())
console.log(
"Length of durationB in hours is:", durationB.asHours(
))
console.log("durationB hours is:", durationB.hours())
输出:
Length of durationA in hours is: 50
durationA hours is: 2
Length of durationB in hours is: 64
durationB hours is: 16
参考: https://momentjs.com/docs/#/durations/hours/