Phương thức setMilliseconds() thiết lập mili-giây (0-999) cho đối tượng Date theo thời gian địa phương. Trả về timestamp mới.
Cú pháp
dateObj.setMilliseconds(ms)
ms: Mili-giây (0-999). Vượt phạm vi -> auto normalize- Trả về: Timestamp mới (number)
Ví dụ cơ bản
const date = new Date('1989-09-26T12:04:25.096');
date.setMilliseconds(225);
console.log(date.getMilliseconds()); // 225
Thiếu ms khi tạo Date
const date = new Date('1989-09-26T12:04:25'); // Không có ms
date.setMilliseconds(225);
console.log(date.getMilliseconds()); // 225
Ngày hiện tại set ms
const date = new Date();
date.setMilliseconds(55);
console.log(date.toString()); // Thời gian đầy đủ
console.log(date.getMilliseconds()); // 55
Auto-normalize vượt phạm vi
const date = new Date('1989-09-26T12:04:25.000');
date.setMilliseconds(1500); // 1500ms = 1.5s
console.log(date.getMilliseconds()); // 500
console.log(date.getSeconds()); // 26 (25 + 1)
date.setMilliseconds(-500); // Lùi 500ms
console.log(date.getMilliseconds()); // 500 (1000 - 500)
console.log(date.getSeconds()); // 25 (26 - 1)
Ứng dụng
- Làm tròn timestamp:
date.setMilliseconds(0) - Test deterministic: set ms cố định
- Benchmark: đo độ chính xác ms
- Game/animation: sync timestamp
Lưu ý
- Phạm vi: 0-999
- Vượt phạm vi auto-normalize (tràn sang giây)
- Làm thay đổi object Date gốc
- Khác với
setUTCMilliseconds()(UTC) - Cặp đôi với
getMilliseconds() - Độ chính xác thực tế ~1ms (browser)