moment.js moment().startOf() 方法

moment.js moment().startOf() 方法

moment().startOf() 方法 用于改变 Moment 对象,使其设置为给定时间单位的开始。可用的时间单位包括:年、月、季度、周、天、小时、分钟和秒。

语法:

moment().startOf( String );

参数: 此方法接受一个单一的参数,如上所述,并在下面进行描述:

  • String: 它是时间单位,从该时间单位开始设置Moment对象。

返回值: 此方法返回设置了值后的变异Moment对象。

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

以下命令可用于安装moment.js:

安装moment模块:

npm install moment

下面的示例将演示Moment.js的moment().startOf()方法。

示例1:

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:

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/

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程