GetMonth Counts Months From Zero
getMonth returns 0-11 and getDay puts Sunday at 0, so labels need lookup tables and month 12 in the constructor rolls into the next year.
Code
// getMonth 返回 0-11:一月是 0,十二月是 11
const march = new Date(2026, 2, 15); // 构造器里的月份同样从 0 计
console.log('constructor month 2 is:', march.getMonth(), '=> March');
// 人类可读标签:用月名数组按索引取,而不是 getMonth() + 1 硬凑
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
console.log('label:', `${MONTHS[march.getMonth()]} ${march.getDate()}, ${march.getFullYear()}`);
// 常见错误:把 getMonth() 直接当人类月号用
console.log('index vs human number:', march.getMonth(), 'vs', march.getMonth() + 1);
// getDay 同样从零计:0 是周日,6 是周六
const saturday = new Date(2026, 2, 14);
console.log('weekday index:', saturday.getDay(), '(6 = Saturday)');
// 溢出自动进位:month 12 等于次年 1 月
const nextJanuary = new Date(2026, 12, 1);
console.log('month 12 rolls:', nextJanuary.getFullYear(), nextJanuary.getMonth());Output
Captured from a sandboxed run of this snippet in the build pipeline.
constructor month 2 is: 2 => March
label: Mar 15, 2026
index vs human number: 2 vs 3
weekday index: 6 (6 = Saturday)
month 12 rolls: 2027 0Months count from zero
new Date(2026, 2, 15) constructs March — the constructor’s month field is zero-based like getMonth(). The demo prints constructor month 2 is: 2 => March and contrasts index vs human number: 2 vs 3, the classic off-by-one when feeding getMonth() straight into display.
Labels via lookup
Instead of getMonth() + 1 arithmetic, the MONTHS array maps the zero-based index directly to a name; the label line prints Mar 15, 2026 from that table.
Weekday and overflow
getDay() is likewise zero-based with Sunday at 0, so 2026-02-14 prints weekday index: 6 (6 = Saturday). Out-of-range inputs roll over: new Date(2026, 12, 1) prints month 12 rolls: 2027 0 — January of the next year.
Interactive Tools for This Topic
FAQ
- Why does new Date(2026, 12, 1) become January 2027?
- Month inputs outside 0-11 are normalized by rolling over, so month 12 resolves to January of the next year.
- How should month labels be produced?
- Look up a name from an array indexed by the zero-based getMonth() value, as the MONTHS table does — not by adding 1 and hoping the consumer understands.
Report a problem with this exampleOpens a pre-filled issue on GitHub.