Date.getMonth() คืออะไร
เมธอด Date.prototype.getMonth() คืนค่า เดือน (month) ของ Date object ตาม เวลาท้องถิ่น (local time) ค่าที่ได้อยู่ในช่วง 0-11 โดยที่ 0 = มกราคม, 11 = ธันวาคม
⚠️ จุดสำคัญ: Month เป็น zero-based (0-indexed) ซึ่งต่างจากวันที่ (1-31) และปี (full year) นี่คือแหล่ง bug บ่อยที่สุดในการจัดการวันที่ JavaScript
ไวยากรณ์ (Syntax)
dateObj.getMonth()
คืนค่า: จำนวนเต็ม 0-11 แทนเดือน
ตัวอย่างการใช้งาน
ตัวอย่างที่ 1: การใช้งานพื้นฐาน
const date = new Date('1989-09-26T12:04:25');
console.log(date.getMonth()); // 8 (กันยายน = เดือนที่ 9 -> index 8)
ตัวอย่างที่ 2: ไม่ได้ระบุเดือน
const date = new Date('1989 12:04:25'); // ไม่มีเดือน
console.log(date.getMonth()); // 0 (มกราคม - default)
ตัวอย่างที่ 3: เดือนปัจจุบัน
const now = new Date();
console.log(`เดือนปัจจุบัน: ${now.getMonth() + 1}`); // +1 เพื่อได้ 1-12
ตัวอย่างที่ 4: แปลงเป็นชื่อเดือน
const monthNames = [
'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน',
'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม',
'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'
];
const date = new Date('1989-09-26');
console.log(monthNames[date.getMonth()]); // "กันยายน"
// หรือใช้ Intl API (แนะนำ)
console.log(new Intl.DateTimeFormat('th-TH', { month: 'long' }).format(date)); // "กันยายน"
console.log(new Intl.DateTimeFormat('en-US', { month: 'long' }).format(date)); // "September"
UTC Version: getUTCMonth()
const date = new Date('1989-09-26T12:04:25Z');
console.log('Local month:', date.getMonth()); // ขึ้นกับ timezone
console.log('UTC month:', date.getUTCMonth()); // 8 เสมอ
Month Index Mapping
| Index | Month (EN) | Month (TH) | Days |
|---|---|---|---|
| 0 | January | มกราคม | 31 |
| 1 | February | กุมภาพันธ์ | 28/29 |
| 2 | March | มีนาคม | 31 |
| 3 | April | เมษายน | 30 |
| 4 | May | พฤษภาคม | 31 |
| 5 | June | มิถุนายน | 30 |
| 6 | July | กรกฎาคม | 31 |
| 7 | August | สิงหาคม | 31 |
| 8 | September | กันยายน | 30 |
| 9 | October | ตุลาคม | 31 |
| 10 | November | พฤศจิกายน | 30 |
| 11 | December | ธันวาคม | 31 |
กรณีการใช้งานทั่วไป
- Date formatting: แสดงชื่อเดือนใน UI
- Month-based logic: รายงานรายเดือน, billing cycles
- Calendar UI: แสดงปฏิทิน
- Date validation: ตรวจสอบวันที่ถูกต้องตามเดือน
- Grouping data: จัดกลุ่มข้อมูลตามเดือน
ตัวอย่าง: Days in Month
function getDaysInMonth(year, monthIndex) {
// monthIndex: 0-11
return new Date(year, monthIndex + 1, 0).getDate();
}
console.log(getDaysInMonth(2024, 1)); // 29 (กุมภาพันธ์ 2024 - leap year)
console.log(getDaysInMonth(2023, 1)); // 28 (กุมภาพันธ์ 2023)
console.log(getDaysInMonth(2024, 8)); // 30 (กันยายน)
ข้อควรระวัง
- Zero-based (0-11) - ต้อง +1 เพื่อแสดงผลให้ผู้ใช้
- คืนค่า local time - ใช้
getUTCMonth()สำหรับ UTC - Invalid Date -> คืนค่า
NaN - ค่าที่ล้น (month > 11 หรือ < 0) จะถูก normalize อัตโนมัติ