Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức Date.getMilliseconds() trong JavaScript

Phương thức getMilliseconds() trả về mili-giây (0-999) của đối tượng Date theo thời gian địa phương.

Cú pháp

dateObj.getMilliseconds()
  • Trả về: Số nguyên 0-999
  • Không nhận tham số

Ví dụ cơ bản

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

Thiếu mili-giây

const date = new Date('1989-09-26T12:04:25');
console.log(date.getMilliseconds()); // 0 (mặc định)

Ngày hiện tại

const now = new Date();
console.log(now.getMilliseconds()); // Mili-giây hiện tại

Giá trị vượt phạm vi (Normalization)

const date = new Date('1989-09-26T04:50:12.1035'); // 1035 ms = 1.035s
console.log(date.getMilliseconds()); // 35 (1035 % 1000)
console.log(date.getSeconds());      // 13 (12 + 1 giây tràn)

Ứng dụng

  • Timestamp độ chính xác cao: logging, profiling
  • Animation frame timing (requestAnimationFrame)
  • Game loop, physics simulation
  • Benchmark microsecond: performance.now() tốt hơn
  • Unique ID: Date.now() + Math.random() hoặc nanoid

Lưu ý

  • Phạm vi: 0-999
  • Vượt phạm vi auto-normalize (tràn sang giây)
  • Độ chính xác thực tế phụ thuộc hệ thống (thường 1ms)
  • Dùng performance.now() cho sub-millisecond accuracy
  • Trả về NaN nếu Date invalid
  • Có phiên bản UTC: getUTCMilliseconds()