自然年月的概念
所謂自然月,是指每個月的1號到月底;自然年,是指每年的1月1號至12月31號。 而每個月的天數(shù)是不一樣的,故而自然年月的計算,不能用通過減去固定天數(shù)的方式來計算。 如5月31號的上一個月,是4月30號,通過減去30天來計算就錯了;同樣,若只是月份減1,日期不變的話,也不對,會變成4月31號,但4月只有30天,js會自動進(jìn)位到5月1號。 下面介紹兩行代碼即可搞定的自然年月計算的方法。
兩行代碼搞定自然月的計算
知識點(diǎn):
- 先要獲取目標(biāo)月份的天數(shù),怎么獲取的簡單技巧,這個是關(guān)鍵:
new Date(year, month+step+1, 0), 其中,在加了步進(jìn)月數(shù)step后,再+1, 即month+step+1,然后日期設(shè)置為0,這行代碼的意思是:再取目標(biāo)月份的下一個月份1號的前1天(1-1=0)這樣就得到了目標(biāo)月份的最后一天的日期,也即了目標(biāo)月份的天數(shù)。 - 目標(biāo)日期與目標(biāo)月份的天數(shù)對比,取最小的,即是目標(biāo)日期,比如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()));
}
當(dāng)然,為了方便,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
}
})
}
聲明:本文由網(wǎng)站用戶香香發(fā)表,超夢電商平臺僅提供信息存儲服務(wù),版權(quán)歸原作者所有。若發(fā)現(xiàn)本站文章存在版權(quán)問題,如發(fā)現(xiàn)文章、圖片等侵權(quán)行為,請聯(lián)系我們刪除。