1. 程式人生 > 實用技巧 >JS中怎樣獲取當前日期的前一個月和後一個月的日期字串

JS中怎樣獲取當前日期的前一個月和後一個月的日期字串

場景

前端使用日期選擇控制元件在剛進入頁面時開始時間和結束時間預設賦值為當前日期的一個月前和一個月後。

並且賦值的格式為"2020-10-9"這種日期字串格式。

注:

部落格:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程式猿
獲取程式設計相關電子書、教程推送與免費下載。

實現

      var lastMonthToday = new Date(
        new Date().getTime() - 30 * 24 * 60 * 60 * 1000
      );
      var lastMonthYear = lastMonthToday.getFullYear();
      
var lastMonth = lastMonthToday.getMonth() + 1; var lastMonthDay = lastMonthToday.getDate < 10 ? "0" + lastMonthToday.getDate : lastMonthToday.getDate(); var lastMonthKsrq = lastMonthYear + "-" + lastMonth + "-" + lastMonthDay; var nextMonthToday = new Date(
new Date().getTime() + 30 * 24 * 60 * 60 * 1000 ); var nextMonthYear = nextMonthToday.getFullYear(); var nextMonth = nextMonthToday.getMonth() + 1; var nextMonthDay = nextMonthToday.getDate < 10 ? "0" + nextMonthToday.getDate : nextMonthToday.getDate();
var nextMonthJsrq = nextMonthYear + "-" + nextMonth + "-" + nextMonthDay;