当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Moment.js moment().day()用法及代码示例


的`moment().day()` 函数用于检索或修改 Moment 对象中的星期几。星期几由 0 到 6 之间的值表示,其中 0 对应星期日,6 对应星期六。如果指定的值超出此范围,则会相应地回绕到前几周或后几周。请务必注意,此方法对区域设置不敏感,因此无论区域设置如何,与值关联的日期都将保持不变。

用法:

moment().weekday( Number );

参数:该方法接受如上所述和如下所述的单个参数:

  • Number:这是必须为 Moment 对象设置的星期几。它是一个可选参数。

返回值:此方法返回 Moment 所在星期的当前日期。

注意:这在普通的 Node.js 程序中不起作用,因为它需要全局安装或在项目目录中安装外部moment.js 库。

Moment.js 可以使用以下命令安装:

moment模块的安装:

npm install moment

示例 1:以下示例将演示Moment.jsmoment().day()方法.

Javascript


const moment = require('moment');
console.log("Current Date:", moment().toString())
console.log("Current day is:", moment().day())
let thisWeekWednesday = moment().day(3);
console.log(
    "This week's Wednesday is:",
    thisWeekWednesday.toString()
)
let thisWeekSaturday = moment().day(6);
console.log(
    "This week's Saturday is:",
    thisWeekSaturday.toString()
)
let thisWeekMonday = moment().day(1);
console.log(
    "This week's Monday is:",
    thisWeekMonday.toString()
)

输出:

Current Date: Mon Jul 18 2022 01:21:54 GMT+0530
Current day is: 1
This week's Wednesday is: Wed Jul 20 2022 01:21:54 GMT+0530
This week's Saturday is: Sat Jul 23 2022 01:21:54 GMT+0530
This week's Monday is: Mon Jul 18 2022 01:21:54 GMT+0530

示例 2:以下示例将演示Moment.jsmoment().day()方法.

Javascript


const moment = require('moment');
console.log("Current Date:", moment().toString())
console.log("Current day is:", moment().day())
// Next week is 7 (full week) + 3 (for Wednesday) = 10
let nextWeekWednesday = moment().day(10);
console.log(
    "Next week's Wednesday is:",
    nextWeekWednesday.toString()
)
// Previous week is 3 (for Wednesday) - 7 (full week) = -4
let prevWeekWednesday = moment().day(-4);
console.log(
    "Previous week's Wednesday is:",
    prevWeekWednesday.toString()
)
// Next week is 7 (full week) + 7 (for sunday) = 14
let nextWeekSunday = moment().day(14);
console.log(
    "Next week's Sunday is:",
    nextWeekSunday.toString()
)

输出:

Current Date: Mon Jul 18 2022 01:21:54 GMT+0530
Current day is: 1
Next week's Wednesday is: Wed Jul 27 2022 01:21:54 GMT+0530
Previous week's Wednesday is: Wed Jul 13 2022 01:21:54 GMT+0530
Next week's Sunday is: Sun Jul 31 2022 01:21:54 GMT+0530


相关用法


注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 Moment.js moment().day() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。