自然月的計算
開發(fā)中經(jīng)常碰到需要計算自然月的問題薄料,比如篩選條件取最近一個月、最近三個月等泵琳。計算自然月的日期摄职,不能通過簡單的通過30天*倍數(shù)來計算,否則會有很大的誤差获列,而是需要考慮跨月份的問題谷市。如5月31號的上一個月,其實是4月30號击孩,而不是4月31號迫悠,因為4月沒有31號;4月30號的上個月是3月30號巩梢,而不是3月31號创泄。
下面介紹兩行代碼即可搞定的自然年月計算的方法艺玲。
兩行代碼搞定自然月的計算
知識點:
- 先要獲取目標月份的天數(shù),怎么獲取的簡單技巧鞠抑,這個是關鍵:
new Date(year, month+step+1, 0), 其中,
在加了步進月數(shù)step后饭聚,再+1, 即month+step+1,然后日期設置為0搁拙,
這行代碼的意思是:再取目標月份的下一個月份1號的前1天(1-1=0)
這樣就得到了目標月份的最后一天的日期秒梳,也即了目標月份的天數(shù)。 - 目標日期與目標月份的天數(shù)對比感混,取最小的端幼,即是目標日期,比如3月31號的下一個月是4月30號弧满,而不是4月31號
natureMonth(curDate, step){
let targetDateLastDay = new Date(curDate.getFullYear(), curDate.getMonth() + step + 1, 0);
return new Date(curDate.getFullYear(), curDate.getMonth() + step, Math.min(curDate.getDate(), targetDateLastDay.getDate()));
}
當然婆跑,為了方便,curDate可以添加支持string類型庭呜,并且返回yyyy-MM-dd類型的日期字符串
故最終代碼為
natureMonth(curDate, step) {
if (!curDate || !step) return curDate;
if (typeof curDate === 'string') curDate = new Date(curDate.replace(/[\/|\.]/g, '-')) // new Date(str) 對str格式的滑进,ios只支持yyyy-MM-dd
let targetDateLastDay = new Date(curDate.getFullYear(), curDate.getMonth() + step + 1, 0);
let targetDate = new Date(curDate.getFullYear(), curDate.getMonth() + step, Math.min(curDate.getDate(), targetDateLastDay.getDate()));
return formatDate(targetDate, 'yyyy-MM-dd')
}
formatDate(dateObj, format) {
let month = dateObj.getMonth() + 1,
date = dateObj.getDate();
return format.replace(/yyyy|MM|dd/g, field => {
switch (field) {
case 'yyyy':
return dateObj.getFullYear();
case 'MM':
return month < 10 ? '0' + month : month;
case 'dd':
return date < 10 ? '0' + date : date
}
})
}