核心函數
function calcLeaveDate(startDateStr, addDays) {
var parts = startDateStr.split('-'); // "2024-05-20"
var date = new Date(parts[0], parts[1] - 1, parseInt(parts[2]) + addDays);
// JS Date 自動處理月份/年份進位
var week = ['周日','周一','周二','周三','周四','周五','周六'];
var month = date.getMonth() + 1;
var day = date.getDate();
return month + '月' + day + '日 <br> ' + week[date.getDay()] + ' 離店';
}
// 使用
var result = calcLeaveDate('2024-05-20', 3); // "5月23日
周四 離店"
關鍵點
new Date(year, monthIndex, day) 中月份索引 0-11,需 -1
- 日參數超出當月天數會自動進位到下月
getDay() 返回 0-6 對應周日-周六
現代寫法(使用 dayjs)
const dayjs = require('dayjs');
dayjs('2024-05-20').add(3, 'day').format('M月D日 dddd');