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