1、通过各种工具中内置的date对象来获取,默认只有通用的日期对象操作方法下,可以想办法获取该月最后一天。
具体思路是先获取下个月的第一天,在这一天的时间减一天的时间就是本月的最后一天,然后就可以通过getDate()等方法获取‘日’即为所求的每月总数
例子:
getLastDay() {
var new_year = this.currentSelectDate.getFullYear(); //取当前的年份
var new_month = this.currentSelectDate.getMonth()+1; //取下一个月 (getMonth返回0到11)
if (new_month == 12) {
new_month -= 12;
new_year++;
}
var new_date = new Date(new_year, new_month, 1); //取下一个月中的第一天
return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();
}
2、如果只有月份
由于每年只有2月的总天数是不固定的,则需要额外判断该年是否为闰年,是则2月为29号,否则为28号
data:{daysInMonth : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]}
getMonthDays(month) {
var date = new Date();
var m = month;
function isLeapYear(date) {
var year = date.getFullYear();
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)));
}
return m == 1 && isLeapYear(date) ? 29 : this.daysInMonth[m];
}