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 (new Date()) {
var strDate = getFullYear() + "年" + (getMonth()+1) + "月" + getDate() + "日" +
getHours() + ":" + getMinutes() + ":" + getSeconds();
alert(strDate);
}
with 污染作用域、嚴格模式禁用、優化器難處理,**已棄用**。
| 方法 | 返回 | 範圍/說明 |
|---|---|---|
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 至今 |
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"
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); // 區間格式化
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分"
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'})。