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

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

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

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

ไวยากรณ์ (Syntax)

dateObj.getMilliseconds()

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

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

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

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

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

const date = new Date('1989-09-26T04:50:12');
console.log(date.getMilliseconds()); // 0 (default)

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

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

ตัวอย่างที่ 4: ค่าที่ล้น (Overflow)

// มิลลิวินาที 1035 -> normalize
const date = new Date('1989-09-26T04:50:12.1035');
console.log(date.getMilliseconds()); // 35 (1035 - 1000 = 35, วินาทีเพิ่ม 1)
// หมายเหตุ: ตัวอย่างเดิมแสดง 0 ซึ่งอาจเป็นพฤติกรรมเก่า
// มาตรฐานปัจจุบัน: จะ normalize อัตโนมัติ

UTC Version: getUTCMilliseconds()

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

console.log('Local ms:', date.getMilliseconds());     // ขึ้นกับ timezone
console.log('UTC ms:', date.getUTCMilliseconds());    // 96 เสมอ

Precision และ Performance

// Date.getMilliseconds() ให้ precision แค่ milliseconds
// สำหรับ high-resolution timing ใช้ performance.now()

const start = performance.now();
// ... some operation ...
const end = performance.now();
console.log(`Took ${(end - start).toFixed(3)} ms`); // sub-millisecond precision

// Date.now() ให้แค่ millisecond precision
const start2 = Date.now();
// ... 
const end2 = Date.now();
console.log(`Took ${end2 - start2} ms`); // integer milliseconds

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

  • High-precision timestamps: Logging, profiling (แต่ performance.now() ดีกว่า)
  • Unique IDs: timestamp + milliseconds สำหรับ ID แบบ rough
  • Animation/Frame timing: คำนวณ frame duration
  • Benchmarking: วัดเวลาการทำงาน (ร่วมกับ Date.now())
  • Time formatting: แสดงเวลา HH:MM:SS.mmm

ตัวอย่าง: ISO-like Time String with Milliseconds

function formatTimeWithMs(date = new Date()) {
  const h = String(date.getHours()).padStart(2, '0');
  const m = String(date.getMinutes()).padStart(2, '0');
  const s = String(date.getSeconds()).padStart(2, '0');
  const ms = String(date.getMilliseconds()).padStart(3, '0');
  return `${h}:${m}:${s}.${ms}`;
}

console.log(formatTimeWithMs()); // "14:30:45.123"

ข้อควรระวัง

  • คืนค่า local time - ใช้ getUTCMilliseconds() สำหรับ UTC
  • ค่าอยู่ในช่วง 0-999 เสมอ
  • Invalid Date -> คืนค่า NaN
  • ค่าที่ล้นจะถูก normalize อัตโนมัติ
  • สำหรับ high-resolution timing จริง ใช้ performance.now() แทน
  • JavaScript Date precision จำกัดที่ milliseconds (ไม่รองรับ microseconds/nanoseconds)