欧美一区二区国产,亚洲午夜久久久久久久,国产精品一区一区,性爱视频在线播放

自然月是什么意思?解析自然月和整月的區別

自然年月的概念

所謂自然月,是指每個月的1號到月底;自然年,是指每年的1月1號至12月31號。 而每個月的天數是不一樣的,故而自然年月的計算,不能用通過減去固定天數的方式來計算。 如5月31號的上一個月,是4月30號,通過減去30天來計算就錯了;同樣,若只是月份減1,日期不變的話,也不對,會變成4月31號,但4月只有30天,js會自動進位到5月1號。 下面介紹兩行代碼即可搞定的自然年月計算的方法。

兩行代碼搞定自然月的計算

知識點:
  1. 先要獲取目標月份的天數,怎么獲取的簡單技巧,這個是關鍵:
    new Date(year, month+step+1, 0), 其中,在加了步進月數step后,再+1, 即month+step+1,然后日期設置為0,這行代碼的意思是:再取目標月份的下一個月份1號的前1天(1-1=0)這樣就得到了目標月份的最后一天的日期,也即了目標月份的天數。
  2. 目標日期與目標月份的天數對比,取最小的,即是目標日期,比如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
      }
    })
}

聲明:本文由網站用戶香香發表,超夢電商平臺僅提供信息存儲服務,版權歸原作者所有。若發現本站文章存在版權問題,如發現文章、圖片等侵權行為,請聯系我們刪除。

(0)
上一篇 2023年4月8日 15:31:55
下一篇 2023年4月8日 15:47:57

相關推薦

發表回復

您的電子郵箱地址不會被公開。 必填項已用*標注

主站蜘蛛池模板: 台前县| 湖口县| 武功县| 略阳县| 西华县| 天门市| 乌拉特中旗| 井陉县| 彰武县| 台南县| 安仁县| 昆山市| 六枝特区| 青神县| 偏关县| 罗定市| 饶河县| 宣汉县| 阿坝| 确山县| 遂溪县| 双柏县| 奈曼旗| 隆回县| 江口县| 哈巴河县| 兰溪市| 双牌县| 绍兴县| 扎兰屯市| 锡林郭勒盟| 长泰县| 封开县| 抚顺市| 杭锦后旗| 山西省| 额敏县| 青神县| 林口县| 黄骅市| 肥东县|