new Date() 默认输出 ISO 格式,需用 toLocaleString() 或 Intl.DateTimeFormat 实现本地化格式;注意 getMonth() 返回 0–11、补零用 padStart、时区用 IANA ID,复杂场景推荐 dayjs/luxon。
new Date() 返回的对象本身不带格式化能力直接 console.log(new Date()) 会输出类似 2025-05-22T14:32:15.892Z 的 ISO 字符串,这不是你想要的“2025年5月22日 14:32”这种形式。浏览器原生不提供类似 Python 的 strftime 函数,必须手动拼接或借助方法。
toLocaleDateString() 和 toLocaleTimeString()
快速适配本地习惯这两个方法能按用户系统语言/时区自动选择分隔符、顺序和缩写,比硬编码更可靠:
const d = new Date();
console.log(d.toLocaleDateString('zh-CN')); // "2025/5/22"
console.log(d.toLocaleTimeString('zh-CN')); // "下午2:32:15"
console.log(d.toLocaleString('zh-CN')); // "2025/5/22 下午2:32:15"
'en-US'、'ja-JP'),不传则用浏览器默认{ year: 'numeric', month: 'long', day: 'numeric' } → “2025年5月22日”month: '2-digit' 返回 "05",'numeric' 返回 5(无前导零)getMonth() 返回 0–11 是最大陷阱很多人写 date.getMonth() + 1 却忘了加空格或补零,导致 “2025-5-5 9:5:5” 这种丑陋输出。安全做法是封装补零逻辑:
function formatDate(d) {
const pad = n => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
formatDate(new Date()); // "2025-05-22 14:32:15"
getMonth() 返回 0(一月)到 11(十二月),务必 +1getDate() 是“几号”,getDay() 是“星期几”(0=周日),别混用padStart(2, '0') 比 toString().length === 1 ? '0'+n : n 更简洁可靠toUTCString(),用 Intl.DateTimeFormat 或库toUTCString() 固定输出 UTC 时间且格式不可控;toLocaleString() 默认用本地时区。真要指定时区(比如显示东京时间),必须用 Intl.DateTimeFormat:
const d = new Date();
new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Tokyo',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
}).format(d); // "2025/05/22 23:32"
'Asia/Shanghai'、'America/New_York'),不能写 'GMT+8'
dayjs 或 luxon,原生 API 对模糊输入容忍度极低