當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。