/**
* 指定日期的上月同一天,上月没有这天
* @param isRtnNull 如果上月没有这天,是否返回空值,如若不,则返回上月最后一天(默认false)
*/
function getLastMonth(date, isRtnNull=false){
var curdate = date.getDate();
var lastmonth = new Date(date.getTime());// 不直接修改原对象
lastmonth.setDate(0)//上月最后一天,当前月为一月时这种写法会退到上一年十二月
var lastmax = lastmonth.getDate();
if(curdate <= lastmax){//天值不大于上月最大一天,天值同步
lastmonth.setDate(curdate);
} else {
if (isRtnNull) return null;
}
return lastmonth;
}
直接用setMonth(date.getMonth()-1)的话,当7月31号到六月的时候会变为6月1号,所以需要判断一个月多少天,而date.setDate(0);date.getDate();能够得到上一个月有多少天