Moment.js moment.duration().as(String) 方法
方法返回持续时间对象中指定的时间单位。它基本上是其他函数(如asWeeks()、asMonths() 等)的替代品。它还支持moment.add()方法的所有快捷键。
语法:
moment().duration().as(String);
参数: 该方法接受一个参数,如上所述,并在下面进行描述:
- String: 该参数用于指定要将持续时间转换为的时间值类型。
返回值: 该方法返回持续时间的指定单位的请求值。对于所有值而言,无效的持续时间将返回NaN。
注意: 这在正常的Node.js程序中不起作用,因为它需要在全局或项目目录中安装外部的moment.js库。
可以使用以下命令安装Moment.js:
安装moment模块:
npm install moment
以下示例将演示 Moment.js 的 moment.duration().as() 方法。
示例1:
const moment = require('moment');
let durationOne =
moment.duration(2, 'days');
let durationTwo =
moment.duration(5, 'years');
let durationThree =
moment.duration(450, 'seconds');
console.log(
"durationOne as seconds is:",
durationOne.as('seconds')
)
console.log(
"durationTwo as days is:",
durationTwo.as('days')
)
console.log(
"durationThree as minutes is:",
durationThree.as('minutes')
)
输出:
durationOne as seconds is: 172800
durationTwo as days is: 1826
durationThree as minutes is: 7.5
示例2:
const moment = require('moment');
let durationA =
moment.duration({months: 4, days: 5, hours: 9});
let durationB =
moment.duration({hours: 72, minutes: 30});
let durationC =
moment.duration({years: 2, months: 6});
console.log(
"durationA as number of hours is:",
durationA.as('hours')
)
console.log(
"durationB as number of days is:",
durationB.as('days')
)
console.log(
"durationC as number of years is:",
durationC.as('years')
)
输出:
durationA as number of hours is: 3057
durationB as number of days is: 3.0208333333333335
durationC as number of years is: 2.5
示例3:
在这个示例中,我们将了解一些可用的快捷方式。
const moment = require('moment');
let duration1 =
moment.duration({months: 4, days: 5, hours: 9});
let duration2 =
moment.duration({hours: 72, minutes: 30});
let duration3 =
moment.duration({years: 2, months: 6});
// Shorthand for Hours is 'h'
console.log(
"duration1 as number of hours is:",
duration1.as('h')
)
// Shorthand for Days is 'd'
console.log(
"duration2 as number of days is:",
duration2.as('d')
)
// Shorthand for Years is 'y'
console.log(
"duration3 as number of years is:",
duration3.as('y')
)
输出:
duration1 as number of hours is: 3057
duration2 as number of days is: 3.0208333333333335
duration3 as number of years is: 2.5
参考: https://momentjs.com/docs/#/durations/as/