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


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


moment().startOf() 方法用於改變 Moment,以便將其設置為給定時間單位的開始。可用的時間單位可以是年、月、季度、周、日、小時、分鍾和秒。

用法:

moment().startOf( String );

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

  • String:它是將 Moment 對象設置為開始的時間單位。

返回值:此方法返回設置值後的變異 Moment。

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

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

moment模塊的安裝:

npm install moment

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

示例 1:

Javascript


const moment = require('moment'); 
  
console.log("Current moment is:", moment().toString()); 
  
// This will set the moment to 12:00 am today 
console.log( 
    "startOf current moment's day:", 
    moment().startOf('day').toString() 
) 
  
// This will set the moment to the 
// first day and hour of this week 
console.log( 
    "startOf current moment's week:", 
    moment().startOf('week').toString() 
) 
  
// This will set the moment to the 
// first day and hour of this month 
console.log( 
    "startOf current moment's month:", 
    moment().startOf('month').toString() 
) 
  
// This will set the moment to the 
// beginning of the current quarter 
// 1st day and hour of month 
console.log( 
    "startOf current moment's quarter:", 
    moment().startOf('quarter').toString() 
) 
  
// This will set the moment to the 
// first day and hour of the year 
console.log( 
    "startOf current moment's year:", 
    moment().startOf('year').toString() 
)

輸出:

Current moment is: Mon Jul 18 2022 02:33:56 GMT+0530
startOf current moment’s day: Mon Jul 18 2022 00:00:00 GMT+0530
startOf current moment’s week: Sun Jul 17 2022 00:00:00 GMT+0530
startOf current moment’s month: Fri Jul 01 2022 00:00:00 GMT+0530
startOf current moment’s quarter: Fri Jul 01 2022 00:00:00 GMT+0530
startOf current moment’s year: Sat Jan 01 2022 00:00:00 GMT+0530

示例 2:

Javascript


const moment = require('moment'); 
  
console.log("Current moment is:", 
    moment().toString()); 
  
// This will set the moment to the 
// first millisecond of the second  
console.log( 
    "startOf current moment's second:", 
    moment().startOf('second').toString() 
) 
  
// This will set the moment to the 
// first second of the minute  
console.log( 
    "startOf current moment's minute:", 
    moment().startOf('minute').toString() 
) 
  
// This will set the moment to the  
// first minute of the hour  
console.log( 
    "startOf current moment's hour:", 
    moment().startOf('hour').toString() 
)

輸出:

Current moment is: Mon Jul 18 2022 02:33:56 GMT+0530
startOf current moment’s second: Mon Jul 18 2022 02:33:56 GMT+0530
startOf current moment’s minute: Mon Jul 18 2022 02:33:00 GMT+0530
startOf current moment’s hour: Mon Jul 18 2022 02:00:00 GMT+0530

參考:https://momentjs.com/docs/#/manipulating/start-of/



相關用法


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