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

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

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

เมธอด Date.prototype.getTime() คืนค่า ค่าตัวเลข (numeric value) ที่แทนเวลา ของ Date object นั้น ตาม Universal Time (UTC) ค่าที่ได้คือ จำนวนมิลลิวินาทีตั้งแต่ Unix Epoch (1 มกราคม 1970 00:00:00 UTC)

นี่คือวิธีมาตรฐานในการได้ timestamp ของ Date object ใดๆ เพื่อนำไปคำนวณ เปรียบเทียบ หรือเก็บลงฐานข้อมูล

ไวยากรณ์ (Syntax)

dateObj.getTime()

คืนค่า: จำนวนมิลลิวินาทีจาก epoch (Number) - เท่ากับ dateObj.valueOf() และ +dateObj

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

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

const date = new Date('1989-09-26T12:04:25.096Z');
console.log(date.getTime()); // 622794865096

// เทียบเท่ากับ:
console.log(date.valueOf()); // 622794865096
console.log(+date);          // 622794865096

ตัวอย่างที่ 2: Date object ที่ไม่ได้ระบุค่า (Current time)

const now = new Date();
console.log(now.getTime()); // timestamp ปัจจุบัน
console.log(Date.now());    // วิธีเร็วกว่าสำหรับ current timestamp

ตัวอย่างที่ 3: การคำนวณระยะเวลา (Time Difference)

const start = new Date('2024-01-01T00:00:00Z');
const end = new Date('2024-12-31T23:59:59Z');

const diffMs = end.getTime() - start.getTime();
const diffDays = diffMs / (1000 * 60 * 60 * 24);
const diffHours = diffMs / (1000 * 60 * 60);

console.log(`${diffDays.toFixed(1)} วัน`);  // 365.0 วัน
console.log(`${diffHours.toFixed(1)} ชั่วโมง`); // 8759.9 ชั่วโมง

ตัวอย่างที่ 4: การเปรียบเทียบวันที่

const date1 = new Date('2024-01-15');
const date2 = new Date('2024-01-20');

if (date1.getTime() < date2.getTime()) {
  console.log('date1 ก่อน date2');
} else if (date1.getTime() > date2.getTime()) {
  console.log('date1 หลัง date2');
} else {
  console.log('วันที่เท่ากัน');
}

ตัวอย่างที่ 5: การใช้กับ Sorting

const dates = [
  new Date('2024-03-15'),
  new Date('2024-01-10'),
  new Date('2024-02-28')
];

dates.sort((a, b) => a.getTime() - b.getTime());
console.log(dates.map(d => d.toISOString().split('T')[0]));
// ["2024-01-10", "2024-02-28", "2024-03-15"]

getTime() vs Date.now() vs valueOf()

เมธอดใช้กับคืนค่าPerformance
date.getTime()Date instancems from epochNormal
date.valueOf()Date instancems from epochNormal (internal)
+dateDate instancems from epochNormal (coercion)
Date.now()Static (no instance)ms from epoch (now)Fastest

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

  • Timestamp storage: เก็บในฐานข้อมูล (BIGINT, INTEGER)
  • Time calculations: ความแตกต่างระหว่างวันที่, aging, expiration
  • Sorting dates: เรียงลำดับ Date objects
  • Cache invalidation: ตรวจสอบว่า cache หมดอายุหรือยัง
  • Performance measurement: วัดเวลารันโค้ด (แต่ performance.now() แม่นยำกว่า)
  • Unique IDs: timestamp + random สำหรับ simple unique IDs
  • JSON serialization: JSON.stringify(date) ใช้ getTime() ภายใน

ข้อควรระวัง

  • ค่าเป็น มิลลิวินาที ไม่ใช่วินาที (Unix timestamp ทั่วไป = วินาที)
  • แปลงเป็นวินาที: Math.floor(date.getTime() / 1000)
  • แปลงจากวินาที: new Date(unixSeconds * 1000)
  • Range: ประมาณ ±100,000,000 วันจาก epoch (~273,970 ปี)
  • Invalid Date -> คืนค่า NaN

การแปลงหน่วยเวลาที่ใช้บ่อย

const ms = date.getTime();

const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(ms / 60000);
const hours = Math.floor(ms / 3600000);
const days = Math.floor(ms / 86400000);

// กลับกัน
const dateFromSeconds = new Date(seconds * 1000);
const dateFromDays = new Date(days * 86400000);