旅館/民宿預訂系統:使用者選擇入住日期 (如 2024-07-03) 與住宿天數 (如 3 晚),自動計算並顯示退房日期 (月/日/星期)。
function calculateCheckoutDate() {
// 1. 取得輸入值
const inDay = document.getElementById('date_6').value; // "2024-07-03"
const nights = parseInt(document.querySelector('.time_lk').value, 10) || 0; // 3
if (!inDay) return;
// 2. 解析日期 (注意:month 為 0-based)
const [year, month, day] = inDay.split('-').map(Number);
// 3. 建立 Date 物件:直接加天數,Date 內建處理跨月/跨年/閏年
const checkIn = new Date(year, month - 1, day + nights);
// 4. 格式化輸出
const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const outMonth = checkIn.getMonth() + 1; // getMonth() 0-based
const outDay = checkIn.getDate();
const weekday = weekdays[checkIn.getDay()];
const result = `${outMonth}月${outDay}日
${weekday}離店`;
document.querySelector('.time_2').innerHTML = result;
}
| 陷阱 | 錯誤寫法 | 正確寫法 | 原因 |
|---|---|---|---|
| 月份索引 | new Date(year, month, day) | new Date(year, month-1, day) | JS 月份 0=1月, 11=12月 |
| 日期運算 | 字串拼接 month+"/"+day+"/"+year | new Date(year, month-1, day+nights) | Date 建構子自動正規化 (32日→下月1日) |
| 星期陣列 | weekday[0]='周一' | weekday[0]='周日' | getDay() 0=星期日 |
| 字串轉數字 | val * 1 | parseInt(val, 10) | 明確基數,避免八進制誤判 |
const calculateCheckout = () => {
const inDay = document.getElementById('date_6')?.value ?? '';
const nights = parseInt(document.querySelector('.time_lk')?.value ?? '0', 10);
if (!inDay) return;
const [y, m, d] = inDay.split('-').map(Number);
const out = new Date(y, m - 1, d + nights);
const fmt = new Intl.DateTimeFormat('zh-TW', {
month: 'numeric', day: 'numeric', weekday: 'short'
});
const parts = fmt.formatToParts(out);
const outStr = parts.reduce((acc, p) => {
if (p.type === 'month') return acc + p.value + '月';
if (p.type === 'day') return acc + p.value + '日';
if (p.type === 'weekday') return acc + '
' + p.value.replace('週', '周') + '離店';
return acc;
}, '');
document.querySelector('.time_2').innerHTML = outStr;
};
優勢:使用 Intl.DateTimeFormat 內建多語系格式化,自動處理地區差異 (繁中 zh-TW 顯示「周」而非「週」)。
Intl.DateTimeFormat 配合 timeZone 選項)。change 事件觸發計算。