Linux 拨号vps windows公众号手机端

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

lewis 7年前 (2019-01-14) 阅读数 12 #程序编程
文章标签 js

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

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门