用 new Date() 获取当前日期对象,需加 new 关键字;getXXX() 方法读取时间各部分(注意月份从 0 开始);修改日期须用 setXXX();toISOString() 返回 UTC 标准字符串,toLocaleDateString() 按本地时区和语言格式化。

如何用 JavaScript 获取当前日期
直接调用 new Date() 就能拿到当前时间的完整 Date 对象,它基于本地时区。不需要额外参数,也不依赖外部库。
常见误操作是写成 Date()(不带 new),这会返回一个字符串而非对象,后续调用 getFullYear() 等方法会报 TypeError: Date().getFullYear is not a function。
-
new Date()→ 返回Date实例,可链式调用方法 -
Date()→ 返回形如"Mon Apr 01 2024 15:23:45 GMT+0800 (CST)"的字符串 - 如果只需要年月日(比如表单默认值),建议立刻用
getFullYear()、getMonth()、getDate()提取,避免后续格式化出错
获取年月日时分秒的常用方法有哪些
Date 对象提供一组 getXXX() 方法读取各部分值,注意月份从 0 开始计数,而星期几的 getDay() 返回 0(周日)到 6(周六)。
const now = new Date(); console.log(now.getFullYear()); // 2024 console.log(now.getMonth()); // 3(四月 → 索引 3) console.log(now.getDate()); // 1(当月第 1 天) console.log(now.getHours()); // 15(24 小时制) console.log(now.getMinutes()); // 23 console.log(now.getSeconds()); // 45 console.log(now.getDay()); // 1(周一)
想拼接成 "2024-04-01" 这类格式,必须手动补零:String(now.getMonth() + 1).padStart(2, '0'),不能直接用 getMonth() 原值。
立即学习“Java免费学习笔记(深入)”;
toISOString() 和 toLocaleDateString() 的区别在哪
toISOString() 返回标准 UTC 时间字符串(如 "2024-04-01T07:23:45.123Z"),适合 API 传输或数据库存储;toLocaleDateString() 则按用户本地时区和语言习惯格式化(如中文系统下输出 "2024年4月1日"),适合展示给用户。
-
toISOString()永远是 UTC,不随系统时区变化 -
toLocaleDateString()受浏览器语言、时区、甚至用户系统设置影响,同一段代码在不同设备上结果可能不同 - 若需固定格式如
"YYYY-MM-DD"且保持本地时间,别依赖toLocaleDateString(),应手动拼接或用Intl.DateTimeFormat
修改日期(比如加 7 天)为什么不能直接改 getXXX() 返回的值
getXXX() 方法只读,修改它们对原对象无任何影响。要改变日期,必须用 setXXX() 方法,例如加 7 天:
const d = new Date(); d.setDate(d.getDate() + 7); // ✅ 正确:先读再设 // d.getDate() + 7; // ❌ 无效:只是个数字,没赋值也没调 set
容易踩的坑:
-
setMonth(12)会自动进位到下一年的 0 月(即明年 1 月),不是报错 -
setDate(0)是合法的,表示上个月最后一天 - 跨月计算(如“本月最后一天”)建议用
new Date(year, month + 1, 0),比手动判断更可靠
日期计算逻辑比表面看起来复杂,尤其是涉及夏令时、闰年、月末天数不一致时,简单加减容易出错。业务中若频繁操作日期,建议引入 date-fns 或 dayjs 这类库处理边界情况。











