萬盛學電腦網

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

JavaScript 獲取當前系統日期時間:Date 對象格式化完整指南

基礎獲取與拼接

var curr_time = new Date();
var strDate = curr_time.getFullYear() + "年" +
              (curr_time.getMonth() + 1) + "月" +  // 月份 0-11
              curr_time.getDate() + "日" +
              curr_time.getHours() + ":" +
              curr_time.getMinutes() + ":" +
              curr_time.getSeconds();
document.write(strDate); // 2024年1月15日14:30:45

with 語句簡化(不推薦現代使用)

with (new Date()) {
    var strDate = getFullYear() + "年" + (getMonth()+1) + "月" + getDate() + "日" +
                  getHours() + ":" + getMinutes() + ":" + getSeconds();
    alert(strDate);
}

with 污染作用域、嚴格模式禁用、優化器難處理,**已棄用**。

Date 關鍵方法速查表

方法返回範圍/說明
getFullYear()年四位數,如 2024
getMonth()月0-11,**需 +1**
getDate()日1-31
getDay()星期0(日)-6(六)
getHours()時0-23
getMinutes()分0-59
getSeconds()秒0-59
getMilliseconds()毫秒0-999
getTime()時間戳毫秒數,1970-01-01 至今

現代格式化方案

1. toLocaleString 系列(零依賴、本地化)

const now = new Date();
now.toLocaleString('zh-CN', { 
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false 
}); // "2024/01/15 14:30:45"

now.toLocaleDateString('zh-CN'); // "2024/1/15"
now.toLocaleTimeString('zh-CN', {hour12: false}); // "14:30:45"

2. Intl.DateTimeFormat(高性能、可復用)

const fmt = new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false
});
fmt.format(new Date()); // "2024/01/15 14:30:45"
fmt.formatRange(start, end); // 區間格式化

3. 手動模板函數(完全可控)

function formatDate(date, template = 'YYYY-MM-DD HH:mm:ss') {
    const map = {
        YYYY: date.getFullYear(),
        MM: String(date.getMonth()+1).padStart(2,'0'),
        DD: String(date.getDate()).padStart(2,'0'),
        HH: String(date.getHours()).padStart(2,'0'),
        mm: String(date.getMinutes()).padStart(2,'0'),
        ss: String(date.getSeconds()).padStart(2,'0'),
        SSS: String(date.getMilliseconds()).padStart(3,'0')
    };
    return template.replace(/YYYY|MM|DD|HH|mm|ss|SSS/g, m => map[m]);
}
formatDate(new Date(), 'YYYY年MM月DD日 HH時mm分'); // "2024年01月15日 14時30分"

4. 第三方庫:date-fns / dayjs / luxon

import { format } from 'date-fns';
format(new Date(), 'yyyy-MM-dd HH:mm:ss'); // 輕量、模塊化、Tree-shaking

時區處理

  • getTimezoneOffset():返回分鐘差(UTC - 本地),東區為負。
  • toISOString():UTC 時間 2024-01-15T06:30:45.000Z。
  • 跨時區展示:Intl.DateTimeFormat(..., {timeZone: 'America/New_York'})。
copyright © 萬盛學電腦網 all rights reserved