温馨提示×

js获取当前月份的方法有哪些

js
小亿
860
2023-07-28 03:41:52
栏目: 编程语言

  1. 使用Date对象的getMonth()方法,返回值为0-11之间的数字,表示当前月份的索引。需要注意的是,索引从0开始,所以需要加1才能得到实际的月份。

示例代码:

var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
console.log(currentMonth);
  1. 使用toLocaleString()方法,可以返回包含日期和时间的字符串。然后使用正则表达式提取出月份。

示例代码:

var currentDate = new Date();
var currentMonth = currentDate.toLocaleString().match(/(\d{1,2})\/\d{1,2}\/\d{4}/)[1];
console.log(currentMonth);
  1. 使用moment.js库,它提供了丰富的日期和时间操作方法。可以使用moment()函数创建一个Moment对象,然后使用它的month()方法获取当前月份的索引。同样需要注意索引从0开始,需要加1才能得到实际的月份。

示例代码:

var currentMonth = moment().month() + 1;
console.log(currentMonth);

以上是三种常用的方法,可以根据实际需要选择适合的方法来获取当前月份。

0