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


Moment.js moment().week()用法及代碼示例


moment().week()方法用於獲取或設置Moment對象的星期。這是一種區域設置感知方法,因此數字周將根據當前區域設置而有所不同。這會有所不同,因為根據區域設置,一周的第一天可以是星期日或星期一。

注意:當使用此方法設置星期時,星期幾將保持不變。

用法:

moment().week( Number );

Parameters: 該方法接受如上所述和如下所述的單個參數:

  • Number: 這是必須為 Moment 對象設置的周。它是一個可選參數。

返回值:此方法返回 Moment 的當前周。

注意:這在普通的 Node.js 程序中不起作用,因為它需要全局安裝或在項目目錄中安裝外部moment.js 庫。

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

moment模塊的安裝:

npm install moment

以下示例將演示 Moment.js moment().week() 方法。

示例 1:

Javascript


const moment = require('moment'); 
  
console.log("Current Date:", moment().toString()) 
console.log("Current week is:", moment().week()) 
  
let week1 = moment().week(1); 
console.log( 
    "Moment with Week of 1 is:", 
    week1.toString() 
) 
  
let week40 = moment().week(40); 
console.log( 
    "Moment with Week of 40 is:", 
    week40.toString() 
)

輸出:

Current Date: Wed Jul 13 2022 01:02:36 GMT+0530
Current week is: 29
Moment with Week of 1 is: Wed Dec 29 2021 01:02:36 GMT+0530
Moment with Week of 40 is: Wed Sep 28 2022 01:02:36 GMT+0530

示例 2:在此示例中,我們將了解不同區域設置如何影響指定的周。

Javascript


const moment = require('moment'); 
  
console.log("Current Date:", moment().toString()) 
console.log("Current week is:", moment().week()) 
  
let week1en = moment().locale('en').week(1); 
console.log( 
    "Moment with Week of 1 with locale 'en' is:", 
    week1en.toString() 
) 
  
let week1br = moment().locale('br').week(1); 
console.log( 
    "Moment with Week of 1 with locale 'br' is:", 
    week1br.toString() 
) 
  
let week1in = moment().locale('in').week(52); 
console.log( 
    "Moment with Week of 52 with locale 'in' is:", 
    week1in.toString() 
) 
  
let week1fr = moment().locale('fr').week(52); 
console.log( 
    "Moment with Week of 52 with locale 'fr' is:", 
    week1fr.toString() 
)

輸出:

Current Date: Wed Jul 13 2022 01:02:36 GMT+0530
Current week is: 29
Moment with Week of 1 with locale ‘en’ is: Wed Dec 29 2021 01:02:36 GMT+0530
Moment with Week of 1 with locale ‘br’ is: Wed Jan 05 2022 01:02:36 GMT+0530
Moment with Week of 52 with locale ‘in’ is: Wed Dec 21 2022 01:02:36 GMT+0530
Moment with Week of 52 with locale ‘fr’ is: Wed Dec 28 2022 01:02:36 GMT+0530

參考: https://momentjs.com/docs/#/get-set/week/



相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Moment.js moment().week() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。