Yasin

Yasin

JS Date对象getMonth()获取月份为什么要+1

getMonth() 需要 +1 是因为 JavaScript 的 Date 对象的月份是从 0 开始计数的

JavaScript Date 的月份问题

const date = new Date(2024, 0, 15); // 2024年1月15日
console.log(date.getMonth()); // 输出: 0 (代表1月)

const date2 = new Date(2024, 11, 25); // 2024年12月25日
console.log(date2.getMonth()); // 输出: 11 (代表12月)

月份对照表

getMonth() 返回值 实际月份
0 1月 (January)
1 2月 (February)
2 3月 (March)
... ...
10 11月 (November)
11 12月 (December)

你的代码示例

const now = new Date(); // 假设当前是 2024年2月10日

console.log(now.getFullYear()); // 2024
console.log(now.getMonth()); // 1 (代表2月,但我们想要显示2)
console.log(now.getDate()); // 10

// 不加1的结果
[now.getFullYear(), now.getMonth(), now.getDate()].join("/");
// 结果: "2024/1/10" ❌ 错误!应该是2月不是1月

// 加1的正确结果
[now.getFullYear(), now.getMonth() + 1, now.getDate()].join("/");
// 结果: "2024/2/10" ✅ 正确!

为什么 JavaScript 这样设计?

这是历史遗留问题:

  1. 早期设计:JavaScript 的 Date 受到 Java 的影响,Java 也是月份从0开始
  2. 数组索引思维:把月份当作数组索引 months[0], months[1]...
  3. 向后兼容:现在改不了了,会破坏大量现有代码

其他日期组件的情况

const date = new Date(2024, 1, 15); // 注意:这里的1代表2月

console.log(date.getFullYear()); // 2024 ✅ 正常
console.log(date.getMonth()); // 1 ❌ 需要+1才是真实月份
console.log(date.getDate()); // 15 ✅ 正常
console.log(date.getDay()); // 4 ❌ 0=周日, 1=周一...6=周六

推荐做法

// 创建一个辅助函数
function formatDate(date) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 总是记得+1
  const day = date.getDate();

  return `${year}/${month.toString().padStart(2, "0")}/${day.toString().padStart(2, "0")}`;
}

// 或者使用现代API
const date = new Date();
date.toLocaleDateString("zh-CN"); // "2024/2/10"
date.toISOString().split("T")[0]; // "2024-02-10"