จัดการ Date object ใน JavaScript โดยใช้เมธอด get (อ่านค่า) และ set (กำหนดค่า) สำหรับ Year, Month, Day, Hour, Minute, Second, Millisecond รองรับทั้ง Local Time และ UTC
เมธอด Get (อ่านค่า)
| Method | คำอธิบาย | UTC Version |
getDate() | วันของเดือน (1-31) | getUTCDate() |
getDay() | วันของสัปดาห์ (0-6, 0=อาทิตย์) | getUTCDay() |
getFullYear() | ปี (4 หลัก) | getUTCFullYear() |
getHours() | ชั่วโมง (0-23) | getUTCHours() |
getMilliseconds() | มิลลิวินาที (0-999) | getUTCMilliseconds() |
getMinutes() | นาที (0-59) | getUTCMinutes() |
getMonth() | เดือน (0-11, 0=มกราคม) | getUTCMonth() |
getSeconds() | วินาที (0-59) | getUTCSeconds() |
getTime() | มิลลิวินาทีจาก Epoch (Jan 1, 1970) | - |
getTimezoneOffset() | Timezone offset ในนาที | - |
เมธอด Set (กำหนดค่า)
| Method | คำอธิบาย | UTC Version |
setDate() | ตั้งค่าวัน | setUTCDate() |
setFullYear() | ตั้งค่าปี | setUTCFullYear() |
setHours() | ตั้งค่าชั่วโมง | setUTCHours() |
setMilliseconds() | ตั้งค่ามิลลิวินาที | setUTCMilliseconds() |
setMinutes() | ตั้งค่านาที | setUTCMinutes() |
setMonth() | ตั้งค่าเดือน | setUTCMonth() |
setSeconds() | ตั้งค่าวินาที | setUTCSeconds() |
setTime() | ตั้งค่าจาก milliseconds since epoch | - |
เมธอด Format/Parse
| Method | คำอธิบาย |
toString() | สตริงวันที่เต็ม (Local) |
toISOString() | ISO 8601 Format (UTC) - มาตรฐานสำหรับ API |
toLocaleString() | Format ตาม Locale ผู้ใช้ |
toLocaleDateString() | วันที่ตาม Locale |
toLocaleTimeString() | เวลาตาม Locale |
valueOf() | เท่ากับ getTime() |
Date.parse(str) | Static: Parse สตริงเป็น Timestamp |
Date.now() | Static: Timestamp ปัจจุบัน |
ตัวอย่างการใช้งาน
const now = new Date();
console.log(now.getFullYear()); // 2024
console.log(now.getMonth() + 1); // 1-12 (ต้อง +1)
console.log(now.getDate()); // 1-31
console.log(now.getHours()); // 0-23
console.log(now.toISOString()); // "2024-01-15T10:30:00.000Z"
console.log(now.toLocaleString('th-TH')); // "15/1/2567, 17:30:00"
// ตั้งค่า
const birthday = new Date();
birthday.setFullYear(1990);
birthday.setMonth(5); // มิถุนายน (0-indexed)
birthday.setDate(15);
แนะนำ: สำหรับงานวันที่ซับซ้อน ใช้ Library อย่าง date-fns, Luxon, หรือ Day.js (Native Date API มี Bugs และ API ไม่สม่ำเสมอ)