let currentDate = "2019-04"; currentDate = new Date(currentDate); // 將日期格式轉換為 Mon Apr 01 2019 08:00:00 GMT+0800 (中國標准時間) // 月份加一 let lastDate = currentDate.setMonth(currentDate.getMonth() - 1); // 輸出日期格式為毫秒形式1551398400000 lastDate = new Date(lastDate); let lastYear = lastDate.getFullYear(); let lastMonth = checkMonth(lastDate.getMonth() + 1); // 因日期中的月份表示為0-11,所以要顯示正確的月份,需要 + 1 lastDate = lastYear + '-' + lastMonth; // "2019-03" // 月份減一 let nextDate = currentDate.setMonth(currentDate.getMonth() + 1); // 輸出日期格式為毫秒形式1556668800000 nextDate = new Date(nextDate); let nextYear = nextDate.getFullYear(); let nextMonth = checkMonth(nextDate.getMonth() + 1); // 因日期中的月份表示為0-11,所以要顯示正確的月份,需要 + 1 nextDate = nextYear + '-' + nextMonth; // "2019-05"
其中,checkMonth 函數的作用是將單位數的月份前面加 ‘0’,比如:‘7’ 變成 ‘07’,代碼如下所示:
checkMonth (i) { if (i<10){ i="0" + i; } return i; }
參考文檔:https://blog.csdn.net/Dora_5537/article/details/89308860