Date.now() คืออะไร
เมธอดสแตติก Date.now() คืนค่า จำนวนมิลลิวินาทีที่ผ่านมาตั้งแต่ Unix Epoch (1 มกราคม 1970 00:00:00 UTC) จนถึงปัจจุบัน เป็นวิธีที่เร็วที่สุดและทันสมัยที่สุดในการได้ timestamp ปัจจุบันใน JavaScript
แทนที่การใช้ new Date().getTime() หรือ +new Date() ซึ่งต้องสร้างออบเจ็กต์ Date ก่อน
ไวยากรณ์ (Syntax)
Date.now()
คืนค่า: จำนวนเต็มแทนมิลลิวินาทีจาก epoch (Number)
ตัวอย่างการใช้งาน
ตัวอย่างที่ 1: การใช้งานพื้นฐาน
const now = Date.now();
console.log(now); // 1705315200000 (ตัวอย่าง)
// แปลงเป็น Date object
const date = new Date(now);
console.log(date.toISOString()); // 2024-01-15T10:40:00.000Z
console.log(date.toLocaleString()); // 1/15/2024, 5:40:00 PM (ขึ้นกับ locale)
ตัวอย่างที่ 2: การวัดเวลา (Performance Timing)
// วัดเวลาการทำงานของฟังก์ชัน
function measureTime(fn, ...args) {
const start = Date.now();
const result = fn(...args);
const end = Date.now();
console.log(`Function took ${end - start} ms`);
return result;
}
// การใช้งาน
measureTime(() => {
// heavy computation
let sum = 0;
for (let i = 0; i < 1e7; i++) sum += i;
return sum;
});
ตัวอย่างที่ 3: คำนวณอายุ / ระยะเวลา
const birthDate = Date.parse('1990-05-15T00:00:00Z');
const now = Date.now();
const ageMs = now - birthDate;
const ageYears = ageMs / (1000 * 60 * 60 * 24 * 365.25);
console.log(`อายุ: ${Math.floor(ageYears)} ปี`);
ตัวอย่างที่ 4: Timestamp สำหรับ Logging/Database
function logEvent(eventName, data) {
return {
timestamp: Date.now(),
event: eventName,
data: data
};
}
console.log(logEvent('user_login', { userId: 123 }));
// { timestamp: 1705315200123, event: 'user_login', data: { userId: 123 } }
Date.now() vs วิธีอื่นๆ
| วิธี | Code | Performance | คำอธิบาย |
|---|---|---|---|
| Date.now() | Date.now() | ⚡ เร็วที่สุด | ไม่สร้าง object, static method |
| new Date().getTime() | new Date().getTime() | 🐢 ช้ากว่า | สร้าง Date object แล้วเรียก method |
| +new Date() | +new Date() | 🐢 ช้ากว่า | Unary plus operator เรียก valueOf() |
| Date.now() | Number(new Date()) | 🐢 ช้ากว่า | Constructor + Number() |
ประสิทธิภาพ (Performance)
// Benchmark
const iterations = 1_000_000;
console.time('Date.now()');
for (let i = 0; i < iterations; i++) Date.now();
console.timeEnd('Date.now()'); // ~5-10ms
console.time('new Date().getTime()');
for (let i = 0; i < iterations; i++) new Date().getTime();
console.timeEnd('new Date().getTime()'); // ~50-100ms
กรณีการใช้งานทั่วไป
- Performance profiling: วัดเวลาการ execute code
- Timestamps: Logging, database records, cache invalidation
- Rate limiting: ตรวจสอบเวลาผ่านไประหว่าง requests
- Animation timing: คำนวณ delta time ใน game loop
- Unique IDs: รวมกับ random สร้าง ID แบบ rough
- Timeout/Interval calculations: คำนวณเวลาที่เหลือ
ข้อควรระวัง
- ค่าที่ได้เป็น มิลลิวินาที ไม่ใช่วินาที (Unix timestamp ทั่วไปมักเป็นวินาที)
- ขึ้นอยู่กับ system clock - อาจไม่แม่นยำหาก user เปลี่ยนเวลาเครื่อง
- สำหรับ high-resolution timing (sub-millisecond) ใช้
performance.now()แทน - ไม่รองรับ timezone - เป็น UTC เสมอ
Polyfill สำหรับ Browser เก่า
if (!Date.now) {
Date.now = function() {
return new Date().getTime();
};
}