Day.js 月份索引:0-based 的重要概念

核心概念

Day.js 的 .month() 方法使用 0-based 索引,這意味著月份的編號從 0 開始,而不是從 1 開始。

.month(0)  → 1 (January)
.month(1)  → 2 (February)  
.month(2)  → 3 (March)
.month(3)  → 4 (April)
...
.month(11) → 12 (December)

常見陷阱

直接使用數字的錯誤示範

// ❌ 錯誤:直接使用月份數字
dayjs().month(3)  // 實際會設定為4月,不是3月!
dayjs().month(12) // 實際會設定為下一年的1月,不是12月!

正確的使用方式

// ✅ 正確:月份數字需要減1
dayjs().month(3 - 1)   // 正確設定為3月
dayjs().month(12 - 1)  // 正確設定為12月

實際應用範例

處理使用者輸入的月份

當使用者輸入月份字串時,需要進行轉換:

// 使用者輸入格式:"03" (表示3月)
const userInput = "03";
const monthNumber = parseInt(userInput);  // 結果: 3

// 正確的設定方式
const date = dayjs().month(monthNumber - 1);  // 設定為3月

對照表

使用者輸入
預期月份
parseInt() 結果
Day.js 需要的值
實際程式碼

"01"

1月

1

0

.month(0)

"02"

2月

2

1

.month(1)

"03"

3月

3

2

.month(2)

"06"

6月

6

5

.month(5)

"12"

12月

12

11

.month(11)

為什麼是 0-based?

這個設計繼承自 JavaScript 原生 Date 物件

// JavaScript 原生 Date 也是 0-based
new Date(2025, 0, 1)   // 2025年1月1日  
new Date(2025, 2, 15)  // 2025年3月15日
new Date(2025, 11, 31) // 2025年12月31日

Day.js 為了保持與原生 JavaScript 的相容性,採用了相同的索引方式。

取得月份值

讀取月份時也要注意

const date = dayjs('2025-03-15');

console.log(date.month());     // 輸出: 2 (不是 3!)
console.log(date.month() + 1); // 輸出: 3 (正確的月份數字)

格式化顯示

如果要顯示正確的月份數字,可以使用格式化:

const date = dayjs('2025-03-15');

console.log(date.format('MM'));   // 輸出: "03"
console.log(date.format('M'));    // 輸出: "3"
console.log(date.format('MMM'));  // 輸出: "Mar"
console.log(date.format('MMMM')); // 輸出: "March"

實務建議

1. 統一處理月份轉換

建立工具函數來處理月份轉換:

// 將一般月份數字轉為 Day.js 索引
function toMonthIndex(monthNumber) {
  return monthNumber - 1;
}

// 將 Day.js 索引轉為一般月份數字
function fromMonthIndex(monthIndex) {
  return monthIndex + 1;
}

// 使用範例
dayjs().month(toMonthIndex(3));  // 設定為3月

2. 註解說明

在程式碼中加入註解提醒:

// month() 使用 0-based 索引,所以需要減1
const targetMonth = parseInt(userInput) - 1;
dayjs().month(targetMonth);

常見錯誤與除錯

錯誤現象:月份總是多1個月

// 使用者輸入 "06" 想要6月
const input = "06";
const month = parseInt(input);

// ❌ 錯誤:會設定為7月
dayjs().month(month);

// ✅ 正確:設定為6月
dayjs().month(month - 1);

除錯技巧

format() 方法來驗證設定是否正確:

const userMonth = "03";
const result = dayjs().month(parseInt(userMonth) - 1);

console.log(`使用者想要: ${userMonth}月`);
console.log(`實際設定: ${result.format('MM')}月`);
// 應該要一致

記住:Day.js 的月份索引從 0 開始,使用時永遠要記得 ±1 的轉換!

Last updated