Moment.js moment.duration().weeks()方法

557 阅读1分钟

Moment.js moment.duration().weeks()方法

moment().duration().weeks()方法是用来获取持续时间的周数。这个周数是作为天数的一个子集来计算的,因此其数值在0到4之间。计算每个星期的天数长度为7天。

这个方法与asWeeks()方法 不同,asWeeks()方法 返回给定期限的周数长度。

语法。

moment().duration().weeks();

参数。此方法不接受任何参数。

返回值。该 方法返回持续时间的周数(0-4)。

注意: 这在正常的Node.js程序中不会工作,因为它需要在全局或项目目录中安装一个外部的moment.js库。

Moment.js可以用以下命令来安装。

安装moment模块。

npm install moment

下面的例子将演示Moment.js moment.duration().weeks() 方法。

例子1:

Javascript

const moment = require('moment');
let durationOne = moment.duration(3,'weeks');
let durationTwo = moment.duration(6,'weeks');
// This returns 3 as it would be the 3rd week
// in the first month of the duration
console.log(
"durationOne Weeks is:", durationOne.weeks()
)
// This returns 1 as it would be the 1st week
// in the second month of the duration
console.log(
"durationTwo Weeks is:", durationTwo.weeks()
)

输出。

durationOne Weeks is: 3
durationTwo Weeks is: 1

例子2: 这个例子将有助于理解这个方法与asWeeks()的区别,以便更好地理解。

Javascript

const moment = require('moment');
let durationA = moment.duration(30,'days');
let durationB = moment.duration(38,'days');
// The asWeeks() method will return a value
// of the actual number of weeks of the duration
console.log(
"Length of durationA in weeks is:",
durationA.asWeeks()
)
// The weeks() method will return
// the week of the duration
// It can be denoted as floor(numberOfWeeks % 4)
console.log(
"durationA Weeks is:", durationA.weeks()
)
console.log(
"Length of durationB in weeks is:",
durationB.asWeeks()
)
console.log(
"durationB Weeks is:", durationB.weeks()
)

输出。

Length of durationA in weeks is: 4.285714285714286
durationA Weeks is: 4
Length of durationB in weeks is: 5.428571428571429
durationB Weeks is: 1

参考 :https://momentjs.com/docs/#/durations/weeks/