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

js
1739
2023/8/2 3:41:52
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

  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);

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 一文搞懂cjs和mjs如何相互使用