Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ฟังก์ชัน Date.getMinutes() ใน JavaScript

Date.getMinutes() คืออะไร

เมธอด Date.prototype.getMinutes() คืนค่า นาที (minutes) ของ Date object ตาม เวลาท้องถิ่น (local time) ค่าที่ได้อยู่ในช่วง 0-59

ไวยากรณ์ (Syntax)

dateObj.getMinutes()

คืนค่า: จำนวนเต็ม 0-59 แทนนาที

ตัวอย่างการใช้งาน

ตัวอย่างที่ 1: การใช้งานพื้นฐาน

const date = new Date('1989-09-26T12:04:25');
console.log(date.getMinutes()); // 4

ตัวอย่างที่ 2: ไม่ได้ระบุนาที

const date = new Date('1989-09-26'); // เฉพาะวันที่
console.log(date.getMinutes()); // 0 (default)

ตัวอย่างที่ 3: เวลาปัจจุบัน

const now = new Date();
console.log(`นาทีปัจจุบัน: ${now.getMinutes()}`);

UTC Version: getUTCMinutes()

const date = new Date('1989-09-26T12:04:25Z');

console.log('Local minutes:', date.getMinutes());     // ขึ้นกับ timezone
console.log('UTC minutes:', date.getUTCMinutes());    // 4 เสมอ

กรณีการใช้งานทั่วไป

  • Time formatting: สร้างสตริงเวลา HH:MM
  • Scheduling: ตรวจสอบเวลาที่กำหนด (cron-like)
  • Duration calculation: คำนวณความแตกต่างในหน่วยนาที
  • Time rounding: ปัดเศษเวลาเป็นช่วง 5/15/30 นาที

ตัวอย่าง: Time Formatting และ Rounding

Format HH:MM

function formatHM(date = new Date()) {
  const h = String(date.getHours()).padStart(2, '0');
  const m = String(date.getMinutes()).padStart(2, '0');
  return `${h}:${m}`;
}

console.log(formatHM()); // "14:30"

Round to Nearest 15 Minutes

function roundTo15Minutes(date = new Date()) {
  const minutes = date.getMinutes();
  const rounded = Math.round(minutes / 15) * 15;
  const result = new Date(date);
  result.setMinutes(rounded, 0, 0);
  return result;
}

console.log(roundTo15Minutes(new Date('2024-01-15T10:07'))); // 10:00
console.log(roundTo15Minutes(new Date('2024-01-15T10:08'))); // 10:15
console.log(roundTo15Minutes(new Date('2024-01-15T10:22'))); // 10:15
console.log(roundTo15Minutes(new Date('2024-01-15T10:23'))); // 10:30

ข้อควรระวัง

  • คืนค่า local time - ใช้ getUTCMinutes() สำหรับ UTC
  • ค่าอยู่ในช่วง 0-59 เสมอ
  • Invalid Date -> คืนค่า NaN
  • ค่าที่ล้นจะถูก normalize อัตโนมัติ (เช่น 70 นาที -> 10 นาที + 1 ชั่วโมง)