// 獲取下個月的特定一天 getSpecificDayOfNextMonth(day, dayEnd = 0) { let now = new Date(); now.setMonth(now.getMonth() + 1, day); // 設定月份加一,日期設定為特定的一天 if (dayEnd) { const newYear = now.getFullYear(); const newMonth = now.getMonth() + 1; // 注意getMonth()返回的是0-11,所以要加1 const newDay = now.getDate(); // 日期 const newDateTime = `${newYear}-${newMonth}-${newDay} 23:59:59` now = new Date(newDateTime) return now } return now; } // 獲取指定年月的第一天 getFirstDayOfMonth(year, month) { return new Date(year, month - 1, 1); } // 獲取指定年月的最後一天 getLastDayOfMonth(year, month, dayEnd) { let lastDate if (dayEnd) { lastDate = new Date(year, month, 0, 23, 59, 59) } else { lastDate = new Date(year, month, 0); } return lastDate }
// 格式化帶時區的時間 formatDate(date, type = 'date') { if (!date) { return '' } let dateObj = new Date(date); // 'Thu April 12 2021 22:03:00 GMT+0800 (中國標準時間)' let datetime // 獲取年份、月份和日期 let year = dateObj.getFullYear(); let month = dateObj.getMonth() + 1; // 月份是從 0 開始的,所以需要加 1 let day = dateObj.getDate(); let hour = dateObj.getHours(); let minute = dateObj.getMinutes(); let second = dateObj.getSeconds(); // 將月份和日期轉換成兩位數格式 let formattedMonth = month.toString().padStart(2, '0'); let formattedDay = day.toString().padStart(2, '0'); let formattedHour = hour.toString().padStart(2, '0'); let formattedMinute = minute.toString().padStart(2, '0'); let formattedSecond = second.toString().padStart(2, '0'); if (type === 'month') { datetime = year + '-' + formattedMonth } else if (type === 'datetime') { datetime = year + '-' + formattedMonth + '-' + formattedDay + " " + formattedHour + ':' + formattedMinute + ':' + formattedSecond } else { datetime = year + '-' + formattedMonth + '-' + formattedDay } return datetime; }