要在頁面上顯示「現在幾點」,只需要 Date 物件加上字串拼接。這篇把每個取用方法都列出來,方便之後要換格式時直接查。
var date = new Date();
alert(date); // 當前時間
alert(date.toLocaleString()); // 轉化為本地時間
alert(date.getFullYear()); // 年份
alert(date.getMonth() + 1); // 月份,取值 0-11,需加 1
alert(date.getDate()); // 一月中的日期
alert(date.getDay()); // 星期幾
alert(date.getHours()); // 小時
alert(date.getMinutes()); // 分鐘
alert(date.getSeconds()); // 秒
alert(date.getMilliseconds()); // 毫秒
alert(date.getTime()); // 從 1970/1/1 午夜到現在的毫秒值
// 分別獲取年、月、日、時、分、秒
var myDate = new Date();
var year = myDate.getFullYear();
var month = myDate.getMonth() + 1;
var date = myDate.getDate();
var hours = myDate.getHours();
var minutes = myDate.getMinutes();
var seconds = myDate.getSeconds();
// 月份與日期顯示為兩位數字,如 09
if (month < 10) { month = "0" + month; }
if (date < 10) { date = "0" + date; }
// 時間拼接
var dateTime = year + "年" + month + "月" + date + "日"
+ hours + "時" + minutes + "分" + seconds + "秒";
document.write(dateTime); // 印出當前時間
<html>
<head>
<title>印出當前時間</title>
<script>
var myDate = new Date();
var year = myDate.getFullYear();
var month = myDate.getMonth() + 1;
var date = myDate.getDate();
var hours = myDate.getHours();
var minutes = myDate.getMinutes();
var seconds = myDate.getSeconds();
if (month < 10) { month = "0" + month; }
if (date < 10) { date = "0" + date; }
var dateTime = year + "年" + month + "月" + date + "日"
+ hours + "時" + minutes + "分" + seconds + "秒";
document.write(dateTime);
</script>
</head>
<body>
<input type="button" value="click" onclick="show()"/>
</body>
</html>
若只需要「印一次」,上面的寫法就夠了;若要持續更新,把整段包成函式再用 setInterval 每秒呼叫即可。另外 toLocaleString() 或 toLocaleString('zh-TW') 本身就能輸出格式化的時間,如果你的需求是顯示而非進一步運算,用它會比手動拼接省事得多。