萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 時間驗證與轉換工具類:格式化、比較、區間計算完整實作

工具類設計目標

  • 統一日期時間格式化(YYYY-MM-DD、YYYY-MM-DD HH:mm:ss)。
  • 毫秒數 ↔ 日期字串雙向轉換。
  • 常見業務驗證:開始/結束時間邏輯、與當前時間比較、區間長度限制。
  • 常用相對時間快捷取得:今天、明天、最近 N 天。
  • 無外部相依、純函式風格、易於單元測試。

完整程式碼 (ES6 Module / UMD 通用)

/**
 * TimeObjectUtil - 日期時間工具類
 * @author boonyachengdu@gmail.com
 * @date 2024 重構版
 */
const TimeObjectUtil = (() => {
    // 私有輔助:補零
    const pad = n => String(n).padStart(2, '0');

    // 私有輔助:格式化 Date 物件
    const fmt = (date, withTime = true) => {
        const y = date.getFullYear();
        const m = pad(date.getMonth() + 1);
        const d = pad(date.getDate());
        if (!withTime) return `${y}-${m}-${d}`;
        return `${y}-${m}-${d} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    };

    // 私有輔助:統一字串轉 Date(支援 YYYY-MM-DD、YYYY/MM/DD、ISO)
    const parse = str => new Date(str.replace(/-/g, '/'));

    return {
        /** 當前時間毫秒數 */
        getCurrentMsTime() { return Date.now(); },

        /** 毫秒數 → 完整日期時間字串 */
        longMsTimeConvertToDateTime(ms) { return fmt(new Date(ms)); },

        /** 日期字串/Date → 毫秒數 */
        dateToLongMsTime(date) { return parse(date).getTime(); },

        /** 格式化:僅日期 */
        formatterDate(date) { return fmt(date, false); },

        /** 格式化:日期 + 00:00:00 */
        formatterDate2(date) { return fmt(date, false) + ' 00:00:00'; },

        /** 格式化:完整日期時間 */
        formatterDateTime(date) { return fmt(date, true); },

        /** 比較:結束時間 > 開始時間 */
        compareDateEndTimeGTStartTime(start, end) {
            return parse(end) > parse(start);
        },

        /** 驗證:開始時間不得早於當前時間 N 月前 */
        compareRightStartTime(monthsAgo, start) {
            const now = Date.now();
            const startMs = parse(start).getTime();
            const limitMs = monthsAgo * 30 * 86400000; // 近似月份
            return (now - startMs) <= limitMs;
        },

        /** 驗證:結束時間不得早於當前時間 N 月前 */
        compareRightEndTime(monthsAgo, end) {
            const now = Date.now();
            const endMs = parse(end).getTime();
            const limitMs = monthsAgo * 30 * 86400000;
            return (now - endMs) <= limitMs;
        },

        /** 驗證:結束 - 開始 不得超過 N 月 */
        compareEndTimeGTStartTime(months, start, end) {
            const diff = parse(end).getTime() - parse(start).getTime();
            return diff <= months * 30 * 86400000;
        },

        /** 取得最近 N 天區間 [N天前 00:00:00, 今天 00:00:00) */
        getRecentDaysDateTime(days) {
            const now = Date.now();
            const dayMs = 86400000;
            const start = new Date(now - days * dayMs);
            const end = new Date(now);
            return { startTime: this.formatterDate2(start), endTime: this.formatterDate2(end) };
        },

        /** 取得今天區間 [今天 00:00:00, 明天 00:00:00) */
        getTodayDateTime() {
            const now = new Date();
            const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            const tomorrow = new Date(today.getTime() + 86400000);
            return { startTime: this.formatterDate2(today), endTime: this.formatterDate2(tomorrow) };
        },

        /** 取得明天區間 [明天 00:00:00, 後天 00:00:00) */
        getTomorrowDateTime() {
            const now = new Date();
            const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
            const dayAfter = new Date(tomorrow.getTime() + 86400000);
            return { startTime: this.formatterDate2(tomorrow), endTime: this.formatterDate2(dayAfter) };
        }
    };
})();

// 掛載全域 (非模組環境)
if (typeof window !== 'undefined') window.TimeObjectUtil = TimeObjectUtil;
if (typeof module !== 'undefined') module.exports = TimeObjectUtil;

使用範例

// 1. 格式化
console.log(TimeObjectUtil.formatterDateTime(new Date())); // 2024-12-15 14:30:05

// 2. 轉換
const ms = TimeObjectUtil.dateToLongMsTime('2024-01-01');
console.log(TimeObjectUtil.longMsTimeConvertToDateTime(ms)); // 2024-01-01 00:00:00

// 3. 驗證表單
const start = '2024-01-01', end = '2024-01-31';
if (!TimeObjectUtil.compareDateEndTimeGTStartTime(start, end)) {
    alert('結束時間必須大於開始時間');
}
if (!TimeObjectUtil.compareEndTimeGTStartTime(3, start, end)) {
    alert('查詢區間不得超過 3 個月');
}

// 4. 快捷區間(報表預設值)
const last7 = TimeObjectUtil.getRecentDaysDateTime(7);
$('#dateMin').val(last7.startTime);
$('#dateMax').val(last7.endTime);

整合 jQuery UI Datepicker 範例

$('#dateMin, #dateMax').datepicker({
    dateFormat: 'yy-mm-dd',
    onSelect() {
        const s = $('#dateMin').val();
        const e = $('#dateMax').val();
        if (s && e && !TimeObjectUtil.compareDateEndTimeGTStartTime(s, e)) {
            alert('結束日期不能早於開始日期');
            $(this).val(''); // 清空錯誤選擇
        }
    }
});

注意事項與改進方向

  • 月份近似: 代碼以 30 天近似一個月,嚴格業務請改用 date-fns / dayjs 的 addMonths / differenceInCalendarMonths。
  • 時區: 所有運算基於本地時間。跨時區系統請統一使用 UTC / Temporal / Luxon。
  • 不可變性: 內部 parse 會 new Date(),不修改傳入物件。
  • 擴充建議: 加入 addDays、addMonths、isWeekend、getWeekRange 等常用工具函式。

建議: 新專案優先考慮 dayjs (2KB) 或 date-fns (Tree-shakable) 等成熟庫,僅在極度輕量、無建置流程的舊專案中使用本工具類。

copyright © 萬盛學電腦網 all rights reserved