Moment.js moment().weekday(Number) 方法
moment().weekday() 方法 用于获取或设置Moment对象的星期几。它是区域感知的,因此根据周的第一天是星期日还是星期一,值可能会有所不同。当超过星期范围时,它将设置下一周或上一周的星期几。
语法:
moment().weekday( Number );
参数: 该方法接受一个参数,如上所述,并在下面进行描述:
- Number: 这是要设置为Moment对象的工作日。这是一个可选参数。
返回值: 该方法返回Moment的当前工作日。
注意: 在普通Node.js程序中将无法运行,因为它需要全局安装或在项目目录中安装外部的moment.js库。
Moment.js可以使用以下命令进行安装:
安装moment模块:
npm install moment
下面的示例将演示 Moment.js moment().weekday() 方法 。
示例1:
const moment = require('moment');
console.log(
"Current Date:", moment().toString()
)
console.log(
"Current weekday is:", moment().weekday()
)
let thisWeekTuesday = moment().weekday(2);
console.log(
"This week's Tuesday is:",
thisWeekTuesday.toString()
)
let thisWeekFriday = moment().weekday(5);
console.log(
"This week's Friday is:",
thisWeekFriday.toString()
)
let thisWeekSunday = moment().weekday(7);
console.log(
"This week's Sunday is:",
thisWeekSunday.toString()
)
输出:
Current Date: Mon Jul 11 2022 01:30:15 GMT+0530
Current weekday is: 1
This week's Tuesday is: Tue Jul 12 2022 01:30:15 GMT+0530
This week's Friday is: Fri Jul 15 2022 01:30:15 GMT+0530
This week's Sunday is: Sun Jul 17 2022 01:30:15 GMT+0530
示例2:
const moment = require('moment');
console.log(
"Current Date:", moment().toString()
)
console.log(
"Current weekday is:", moment().weekday()
)
// Next week is 7 (full week) + 2 (for tuesday) = 9
let nextWeekTuesday = moment().weekday(9);
console.log(
"Next week's Tuesday is:",
nextWeekTuesday.toString()
)
// Previous week is 2 (for tuesday) - 7 (full week) = -5
let prevWeekTuesday = moment().weekday(-5);
console.log(
"Previous week's Tuesday is:",
prevWeekTuesday.toString()
)
// Next week is 7 (full week) + 7 (for sunday) = 14
let nextWeekSunday = moment().weekday(14);
console.log(
"Next week's Sunday is:",
nextWeekSunday.toString()
)
输出:
Current Date: Mon Jul 11 2022 01:30:15 GMT+0530
Current weekday is: 1
Next week's Tuesday is: Tue Jul 19 2022 01:30:15 GMT+0530
Previous week's Tuesday is: Tue Jul 05 2022 01:30:15 GMT+0530
Next week's Sunday is: Sun Jul 24 2022 01:30:15 GMT+0530
参考: https://momentjs.com/docs/#/get-set/weekday/