Moment.js moment().month() 方法

Moment.js moment().month() 方法

moment().month() 方法 用于获取或设置 Moment 对象的月份。 Moment.js 中的月份是从零开始计数的,因此月份的范围是 0 到 11,其中 0 代表一月,11 代表十二月。超过 11 的值会使月份超过一年而进入下一年。

可以使用月份的全名或简写形式的字符串来设置月份。

语法:

moment().month( Number|String );

参数:

本方法只接受一个参数,如上所述,并在下面进行了描述:

  • Number|String:它是要设置为 Moment 对象的月份。它是可选参数。

返回值:

本方法返回 Moment 对象的当前月份。

注意:

这在正常的 Node.js 程序中不起作用,因为它需要在全局范围内或项目目录中安装外部 moment.js 库。

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

安装 moment 模块:

npm install moment

以下示例将演示”moment().month()”方法。

示例1:

const moment = require('moment'); 
  
console.log("Current Date:", moment().toString()) 
console.log("Current month is:", moment().month()) 
  
let month10 = moment().month(10); 
console.log( 
    "Moment with Month of 10 is:", 
    month10.toString() 
) 
  
let month24 = moment().month(24); 
console.log( 
    "Moment with Month of 24 is:", 
    month24.toString() 
)

输出:

Current Date: Wed Jul 13 2022 01:30:32 GMT+0530
Current month is: 6
Moment with Month of 10 is: Sun Nov 13 2022 01:30:32 GMT+0530
Moment with Month of 24 is: Sat Jan 13 2024 01:30:32 GMT+0530

示例2:

const moment = require('moment'); 
  
console.log("Current Date:", moment().toString()) 
console.log("Current month is:", moment().month()) 
  
let monthDecember = moment().month("December"); 
console.log( 
    "Moment with Month of December is:", 
    monthDecember.toString() 
) 
  
let monthFeb = moment().month("Feb"); 
console.log( 
    "Moment with Month of Feb is:", 
    monthFeb.toString() 
)

输出:

Current Date: Wed Jul 13 2022 01:30:32 GMT+0530
Current month is: 6
Moment with Month of December is: Tue Dec 13 2022 01:30:32 GMT+0530
Moment with Month of Feb is: Sun Feb 13 2022 01:30:32 GMT+0530

参考文献: https://momentjs.com/docs/#/get-set/month/

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程