业务需求中,经常会根据当前时间获取上一个月的时间或者当月的最后一天,由于每个月的天数都不同,为了考虑时间上的准确性我们需要做一些判断和计算,具体方法如下:
/* 获取上一个月时间,返回yyyy-MM-dd字符串
* getLastMonthTime('2020-04-16','date'); date类型
* getLastMonthTime(new Date,'num'); //时间戳类型
* */
function getLastMonthTime(date, type){
var daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if(type == 'date'){ //时间戳格式
date = new Date(date);
}
var strYear = date.getFullYear();
var strDay = date.getDate();
var strMonth = date.getMonth()+1;
//判断二月份天数
if (((strYear % 4) === 0) && ((strYear % 100)!==0) || ((strYear % 400)===0)){
daysInMonth[2] = 29;
}
//判断跨年
if(strMonth - 1 === 0){
strYear -= 1;
strMonth = 12;
}else{
strMonth -= 1;
}
strDay = Math.min(strDay,daysInMonth[strMonth]);
strMonth = strMonth<10?"0"+strMonth:strMonth;
strDay = strDay<10?"0"+strDay:strDay;
return strYear+"-"+strMonth+"-"+strDay;
}
/* 获取每月的最后一天
* date类型为(yyyy-MM-dd HH:mm:ss、yyyy-MM-dd HH:mm、yyyy-MM-dd HH、yyyy-MM-dd 、yyyy-MM)
* */
function getLastDay(date) {
var dateMonth = date.substr(5,2);
var month = ['01','02','03','04','05','06','07','08','09','10','11','12'];
var daysInMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var fullYear = new Date(date).getFullYear();
//判断二月份天数
if (fullYear % 4 == 0 && (fullYear % 100 != 0 || fullYear % 400 == 0)){
daysInMonth[1] = 29;
}
var lastDay = daysInMonth[month.indexOf(dateMonth)];
return lastDay;
}