Date.prototype.toTimeString() 返回 Date 對象的**時間部分**字符串,格式為瀏覽器實現相關的可讀時間字符串(通常包含時區信息)。
dateObj.toTimeString()
無參數。
時間字符串,格式類似:"14:39:07 GMT+0800 (中國標準時間)"
const date = new Date(1993, 6, 28, 14, 39, 7); // 7月 (月份 0-11)
console.log(date.toTimeString());
// "14:39:07 GMT+0800 (中國標準時間)" (時區視環境而定)
console.log(new Date().toTimeString());
// "10:30:45 GMT+0800 (中國標準時間)"
| 方法 | 輸出示例 | 包含內容 |
|---|---|---|
toString() | "Wed Jul 28 1993 14:39:07 GMT+0800" | 完整日期時間 |
toTimeString() | "14:39:07 GMT+0800" | **僅時間 + 時區** |
toDateString() | "Wed Jul 28 1993" | 僅日期 |
toISOString() | "1993-07-28T06:39:07.000Z" | UTC 完整、標準格式 |
toLocaleTimeString() | "下午2:39:07" | 本地化時間(可配置) |
function log(message) {
const time = new Date().toTimeString().split(' ')[0]; // "14:39:07"
console.log(`[${time}] ${message}`);
}
log('用戶登錄'); // [14:39:07] 用戶登錄
function updateClock() {
document.getElementById('clock').textContent =
new Date().toTimeString().split(' ')[0];
}
setInterval(updateClock, 1000);
const date = new Date();
const [hours, minutes, seconds] = date.toTimeString().split(' ')[0].split(':').map(Number);
console.log(hours, minutes, seconds); // 14 39 7
// 更推薦:直接用 get 方法
console.log(date.getHours(), date.getMinutes(), date.getSeconds());
toLocaleTimeString() 或日期庫date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })date.toISOString()(完整 UTC)getHours()、getMinutes()、getSeconds()、getTime()dayjs().format('HH:mm:ss')、date-fns format(date, 'HH:mm:ss')Date.toTimeString() 適合快速調試輸出時間部分,但生產代碼中請使用可控、標準化的格式化方案。