萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

JavaScript 日期計算實用範例:入住日期加天數得退房日期含星期顯示

需求場景

旅館/民宿預訂系統:使用者選擇入住日期 (如 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+"/"+yearnew Date(year, month-1, day+nights)Date 建構子自動正規化 (32日→下月1日)
星期陣列weekday[0]='周一'weekday[0]='周日'getDay() 0=星期日
字串轉數字val * 1parseInt(val, 10)明確基數,避免八進制誤判

現代化改寫 (ES6+ / 可選鏈 / 空值合併)


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 顯示「周」而非「週」)。

常見擴充需求

  • 排除假日/特定不可住日期:需整合行事曆 API 或自訂排除日期集合,迴圈遞增天數直到達到實際住宿夜數。
  • 時區處理:跨時區預訂建議統一儲存 UTC,顯示時轉換至當地時區 (Intl.DateTimeFormat 配合 timeZone 選項)。
  • 日期選擇器聯動:入住日變更時自動更新退房日顯示,可綁定 change 事件觸發計算。
copyright © 萬盛學電腦網 all rights reserved