萬盛學電腦網

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

JavaScript 時間戳轉日期格式完整指南(含 C# DateTime JSON 序列化處理)

時間戳格式對比

格式示例來源單位
Unix 時間戳1705315200標準 API秒
JS 時間戳1705315200000Date.now()毫秒
C# JSON 序列化/Date(1705315200000)/JavaScriptSerializer毫秒
ISO 86012024-01-15T10:30:00.000ZJSON.stringify / .NET Core毫秒

C# /Date(1354116249000)/ 格式解析


/**
 * 解析 C# 舊版 JSON 序列化日期格式
 * @param {String} dateStr - 如 "/Date(1354116249000)/" 或 "/Date(1354116249000+0800)/"
 * @returns {Date|null}
 */
function parseCSharpDate(dateStr) {
    if (!dateStr || typeof dateStr !== 'string') return null;
    
    // 提取毫秒數(支援時區偏移)
    const match = dateStr.match(/\/Date\((-?\d+)(?:([+-])(\d{2})(\d{2}))?\)\//);
    if (!match) return null;
    
    const timestamp = parseInt(match[1], 10);
    let date = new Date(timestamp);
    
    // 處理時區偏移(如 +0800)
    if (match[2]) {
        const sign = match[2] === '+' ? -1 : 1; // JS getTimezoneOffset 符號相反
        const offsetHours = parseInt(match[3], 10);
        const offsetMinutes = parseInt(match[4], 10);
        const totalOffset = sign * (offsetHours * 60 + offsetMinutes);
        date = new Date(date.getTime() + totalOffset * 60 * 1000);
    }
    
    return date;
}

// 測試
console.log(parseCSharpDate("/Date(1354116249000)/"));        // 2012-11-28T10:04:09.000Z
console.log(parseCSharpDate("/Date(1354116249000+0800)/"));   // 2012-11-28T02:04:09.000Z (UTC)

通用格式化函數


/**
 * 格式化日期
 * @param {Date|Number|String} date - Date 對象、時間戳(毫秒)、可解析字符串
 * @param {String} format - 格式模板
 * @returns {String}
 */
function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
    if (!(date instanceof Date)) {
        if (typeof date === 'number') date = new Date(date);
        else if (typeof date === 'string') date = new Date(date);
        else return '';
    }
    if (isNaN(date.getTime())) return 'Invalid Date';
    
    const pad = (n, len = 2) => String(n).padStart(len, '0');
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    const ms = date.getMilliseconds();
    
    return format
        .replace('YYYY', year)
        .replace('YY', String(year).slice(-2))
        .replace('MM', pad(month))
        .replace('M', month)
        .replace('DD', pad(day))
        .replace('D', day)
        .replace('HH', pad(hour))
        .replace('H', hour)
        .replace('mm', pad(minute))
        .replace('m', minute)
        .replace('ss', pad(second))
        .replace('s', second)
        .replace('SSS', pad(ms, 3))
        .replace('SS', pad(Math.floor(ms / 10), 2))
        .replace('S', Math.floor(ms / 100));
}

// 使用示例
const now = new Date();
console.log(formatDate(now));                    // 2024-01-15 10:30:45
console.log(formatDate(now, 'YYYY年MM月DD日'));   // 2024年01月15日
console.log(formatDate(now, 'HH:mm'));           // 10:30
console.log(formatDate(1705315200000));          // 時間戳直接轉換
console.log(formatDate("/Date(1705315200000)/")); // 字符串自動解析

現代原生方案:Intl.DateTimeFormat


// 本地化格式化(無需手寫模板)
const dtf = new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false
});
console.log(dtf.format(new Date())); // 2024/01/15 10:30:45

// 自定義格式
const custom = new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric', month: 'long', day: 'numeric',
    weekday: 'long', hour: '2-digit', minute: '2-digit'
});
console.log(custom.format(new Date())); // 2024年1月15日 星期一 10:30

相對時間格式化


const rtf = new Intl.RelativeTimeFormat('zh-CN', { numeric: 'auto' });

function formatRelative(date) {
    const diff = date.getTime() - Date.now();
    const abs = Math.abs(diff);
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    const month = 30 * day;
    const year = 365 * day;
    
    if (abs < minute) return rtf.format(Math.round(diff / 1000), 'second');
    if (abs < hour) return rtf.format(Math.round(diff / minute), 'minute');
    if (abs < day) return rtf.format(Math.round(diff / hour), 'hour');
    if (abs < month) return rtf.format(Math.round(diff / day), 'day');
    if (abs < year) return rtf.format(Math.round(diff / month), 'month');
    return rtf.format(Math.round(diff / year), 'year');
}

console.log(formatRelative(new Date(Date.now() - 2 * 60 * 1000))); // "2 分鐘前"
console.log(formatRelative(new Date(Date.now() + 3 * 24 * 60 * 60 * 1000))); // "3 天后"

最佳實踐總結

  1. 後端統一輸出 ISO 8601 格式(2024-01-15T10:30:00.000Z),前端 new Date() 直接解析
  2. 避免舊版 JavaScriptSerializer 產生 /Date(...)/ 格式,升級 .NET Core 或配置 JsonSerializerSettings
  3. 3. 前端統一使用 formatDate 工具函數或 Intl.DateTimeFormat 4. 存儲/傳輸統一用 UTC,顯示時按用戶時區轉換 5. 相對時間用 Intl.RelativeTimeFormat 實現國際化
copyright © 萬盛學電腦網 all rights reserved