DIV CSS 佈局教程網

JavaScript 日期運算實戰:一次搞定「一週內」與「一個月內」的時間區間
編輯:關於JavaScript     

後台查詢頁面裡,「近一週」「近一個月」這類快捷篩選按鈕幾乎是標配。本文以一個通話記錄查詢的場景為例,示範如何用原生 JavaScript 完成日期的向前推算,並把結果自動填寫到起始與結束時間兩個輸入框中。

需求拆解

頁面上有三顆按鈕:「不限」「一個月內」「一週內」,右側跟著兩個唯讀的時間輸入框。點擊按鈕後,起始時間被推算為對應的過去日期,結束時間則固定為今天。核心難點在於跨月、跨年的進位處理,以及月份天數不一致(28、29、30、31 天)帶來的邊界問題。

完整實作

<html>
<head>
<title></title>
<script src="../Script/jQuery/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="../Script/MTHCRMWidget/MTHCRMWidget.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
    myClick(); // 頁面載入後掛上點擊事件
});

// 把點擊邏輯集中封裝
function myClick() {
    $(".tbBtn").click(function () {
        var sid = $(this).attr("id");
        var agoDate = "";
        var Cdate = new Date();

        if (sid == "CbtnNull") {
            // 不限:清空兩個輸入框
            $("#txtCallCycleBegin").val("");
            $("#txtCallCyclecurrend").val("");
        } else if (sid == "CbtnMoon") {
            // 一個月內
            agoDate = ProcessDate(30);
            $("#txtCallCycleBegin").val("{0}-{1}-{2}".format(agoDate.Year, agoDate.Moon, agoDate.Day));
            $("#txtCallCyclecurrend").val("{0}-{1}-{2}".format(Cdate.getFullYear(), Cdate.getMonth() + 1, Cdate.getDate()));
        } else {
            // 一週內
            agoDate = ProcessDate(7);
            $("#txtCallCycleBegin").val("{0}-{1}-{2}".format(agoDate.Year, agoDate.Moon, agoDate.Day));
            $("#txtCallCyclecurrend").val("{0}-{1}-{2}".format(Cdate.getFullYear(), Cdate.getMonth() + 1, Cdate.getDate()));
        }
    });
}

// 日期推進入出:傳入 30 代表往前一個月,傳入 7 代表往前七天
function ProcessDate(type) {
    // 1. 取出基準時間的年月日(實務上把 new Date() 換掉即可用於測試)
    var currentTime = new Date("2016-01-02");
    var currentYear = currentTime.getFullYear();
    var currentMoon = currentTime.getMonth() + 1; // getMonth() 從 0 起算,記得 +1
    var currentDay = currentTime.getDate();

    // 2. 依類型推算
    var agoDay = "";
    var agoMoon = currentMoon;
    var agoYear = currentYear;
    var max = "";

    switch (type) {
        case 30:
            agoDay = currentDay + 1;
            agoMoon = currentMoon - 1;
            max = new Date(agoYear, agoMoon, 0).getDate(); // 上個月總天數
            break;
        case 7:
            agoDay = currentDay - 6;
            if (agoDay < 0) {
                agoMoon = currentMoon - 1; // 跨月了,月份往前推一
                max = new Date(agoYear, agoMoon, 0).getDate();
                agoDay = max + agoDay;    // 用上月總天數補回負數
            }
            break;
    }

    // 3. 邊界處理
    if (agoDay > max) {
        agoDay = 1;
        agoMoon += 1;
    }
    if (agoMoon == 0) {          // 一月往前推 => 去年十二月
        agoMoon = 12;
        agoYear = currentYear - 1;
    }

    // 4. 補零格式化
    currentMoon = Appendzero(currentMoon);
    currentDay = Appendzero(currentDay);
    agoMoon = Appendzero(agoMoon);
    agoDay = Appendzero(agoDay);

    // 5. 除錯用輸出
    console.log("當前時間為:{0}-{1}-{2}".format(currentYear, currentMoon, currentDay));
    console.log("推算後的時間為:{0}-{1}-{2}".format(agoYear, agoMoon, agoDay));

    return { "Year": agoYear, "Moon": agoMoon, "Day": agoDay };
}

// 個位數補零
function Appendzero(obj) {
    if (obj < 10) {
        return "0" + obj;
    } else {
        return obj;
    }
}
</script>
</head>
<body>
<input type="button" class="tbBtn" id="CbtnNull" style="background-color:#e3e3e3" value="不限"/>
<input type="button" class="tbBtn" id="CbtnMoon" style="width: 80px; margin-left: 5px; margin-right: 5px;" value="一個月內"/>
<input type="button" class="tbBtn" id="CbtnWeek" style="width: 80px; margin-left: 5px; margin-right: 5px;" value="一週內"/>
<input id="txtCallCycleBegin" type="text"/>
<input id="txtCallCyclecurrend" type="text"/>
</body>
</html>

幾個容易踩到的細節

new Date(agoYear, agoMoon, 0).getDate() 是取得「某月總天數」的經典寫法:日期參數傳 0 會回退到上個月的最後一天,因此只要把目標月份的「下一個月」傳進去、日期給 0,就能拿到該月天數。

另外別忘了 getMonth() 的返回值從 0 開始,這也是為什麼程式裡到處都能看到 + 1 與 - 1。跨月判斷建議一律用「先減、再補」的思路,而不是直接寫 if-else 硬判,程式碼會乾淨很多。

最後,若要正式上線,可把 ProcessDate 中的寫死日期改為 new Date(),並考慮改用 Moment.js、Day.js 這類成熟套件,能省下大量邊界判斷的功夫。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved