取得目前時間只需要一行 new Date(),真正的眉角在「格式化」——月份要補零、要拼上「年月日」,這些都得自己處理。本文示範兩種常見寫法。
<script> var curr_time = new Date(); var strDate = curr_time.getFullYear() + "年"; strDate += (curr_time.getMonth() + 1) + "月"; strDate += curr_time.getDate() + "日 "; strDate += curr_time.getHours() + ":"; strDate += curr_time.getMinutes() + ":"; strDate += curr_time.getSeconds(); document.write(strDate); </script>
<script>
var curr_time = new Date();
with (curr_time) {
var strDate = getFullYear() + "年"; // 取年份
strDate += (getMonth() + 1) + "月"; // 月份從 0 起算,必須 +1
strDate += getDate() + "日 "; // 日
strDate += getHours() + ":"; // 時
strDate += getMinutes() + ":"; // 分
strDate += getSeconds(); // 秒
alert(strDate);
}
</script>
月份要加一。getMonth() 回傳 0 到 11,一月是 0,直接顯示會全都差一個月,這是新手最常踩的雷。
年份用 getFullYear()。早期的 getYear() 在部分瀏覽器會回傳「年份減 1900」的兩位數值,範例中原先寫的 getYear()+1900 就是為了補回來;現在請一律用 getFullYear()。
補零讓格式統一。若要輸出 09:05:03 這種美觀格式,自己寫個小工具函式最省事:
function pad(n) { return n < 10 ? '0' + n : '' + n; }
var d = new Date();
var s = d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
console.log(s); // 例如 2026-08-26 16:33:49
最後提醒:以上取得的是使用者本機的時間。若你需要的是伺服器時間或特定時區,應由後端輸出,或用 toISOString() 取得 UTC 標準格式再自行轉換。另外,with 語句在 strict mode 中是被禁止的,正式專案請直接寫 curr_time.getFullYear() 這種明確形式。
以上就是取得與格式化目前時間的作法,希望對你的 JavaScript 開發有所幫助。