Date.getHours() คืออะไร
เมธอด Date.prototype.getHours() คืนค่า ชั่วโมง (hours) ของ Date object ตาม เวลาท้องถิ่น (local time) ในรูปแบบ 24 ชั่วโมง ค่าที่ได้อยู่ในช่วง 0-23
ไวยากรณ์ (Syntax)
dateObj.getHours()
คืนค่า: จำนวนเต็ม 0-23 แทนชั่วโมง
ตัวอย่างการใช้งาน
ตัวอย่างที่ 1: การใช้งานพื้นฐาน
const date = new Date('1989-09-26T12:04:00');
console.log(date.getHours()); // 12
ตัวอย่างที่ 2: ไม่ได้ระบุเวลา
const date = new Date('1989-09-26'); // เฉพาะวันที่
console.log(date.getHours()); // 0 (midnight)
ตัวอย่างที่ 3: เวลาปัจจุบัน
const now = new Date();
console.log(`ชั่วโมงปัจจุบัน: ${now.getHours()}`); // 0-23
UTC Version: getUTCHours()
const date = new Date('1989-09-26T12:04:25Z');
console.log('Local hours:', date.getHours()); // ขึ้นกับ timezone
console.log('UTC hours:', date.getUTCHours()); // 12 เสมอ
12-hour Format Conversion
function get12HourFormat(date = new Date()) {
const hours24 = date.getHours();
const hours12 = hours24 % 12 || 12; // 0 -> 12
const ampm = hours24 >= 12 ? 'PM' : 'AM';
return { hours12, ampm, hours24 };
}
console.log(get12HourFormat(new Date('2024-01-15T00:00'))); // { hours12: 12, ampm: 'AM', hours24: 0 }
console.log(get12HourFormat(new Date('2024-01-15T12:00'))); // { hours12: 12, ampm: 'PM', hours24: 12 }
console.log(get12HourFormat(new Date('2024-01-15T13:00'))); // { hours12: 1, ampm: 'PM', hours24: 13 }
console.log(get12HourFormat(new Date('2024-01-15T23:00'))); // { hours12: 11, ampm: 'PM', hours24: 23 }
กรณีการใช้งานทั่วไป
- Clock display: แสดงนาฬิกา 12/24 ชั่วโมง
- Business hours: ตรวจสอบว่าอยู่ในช่วงเวลาทำงานหรือไม่
- Scheduling: Cron-like time matching
- Greeting messages: Good morning/afternoon/evening
- Time formatting: สร้างสตริงเวลาต่างๆ
ตัวอย่าง: Business Hours Check
function isBusinessHours(date = new Date(),
startHour = 9, endHour = 17, // 9 AM - 5 PM
workDays = [1,2,3,4,5] // Mon-Fri
) {
const day = date.getDay(); // 0=Sun, 6=Sat
const hour = date.getHours();
if (!workDays.includes(day)) return false;
return hour >= startHour && hour < endHour;
}
console.log(isBusinessHours(new Date('2024-01-15T10:00'))); // true (Mon 10AM)
console.log(isBusinessHours(new Date('2024-01-15T18:00'))); // false (Mon 6PM)
console.log(isBusinessHours(new Date('2024-01-14T10:00'))); // false (Sun)
ตัวอย่าง: Greeting by Time
function getGreeting(date = new Date()) {
const hour = date.getHours();
if (hour < 5) return 'Good night';
if (hour < 12) return 'Good morning';
if (hour < 17) return 'Good afternoon';
if (hour < 21) return 'Good evening';
return 'Good night';
}
console.log(getGreeting(new Date('2024-01-15T06:00'))); // Good morning
console.log(getGreeting(new Date('2024-01-15T14:00'))); // Good afternoon
console.log(getGreeting(new Date('2024-01-15T20:00'))); // Good evening
ข้อควรระวัง
- คืนค่า local time - ใช้
getUTCHours()สำหรับ UTC - รูปแบบ 24 ชั่วโมง (0-23) - ต้องแปลงเองสำหรับ 12 ชั่วโมง
- Invalid Date -> คืนค่า
NaN - ค่าที่ล้นจะถูก normalize อัตโนมัติ (เช่น 25 -> 1 ทวันถัดไป)