Phương thức setSeconds() thiết lập giây (0-59) cho đối tượng Date theo thời gian địa phương, có thể kèm mili-giây. Trả về timestamp mới.
Cú pháp
dateObj.setSeconds(seconds[, ms])
seconds: Giây (0-59). Vượt phạm vi -> auto normalizems: Tùy chọn, mili-giây (0-999)- Trả về: Timestamp mới (number)
Ví dụ cơ bản
const date = new Date('1989-09-26T05:04:25.096Z'); // 05:04:25 UTC
console.log("Trước:", date.toUTCString()); // Tue, 26 Sep 1989 05:04:25 GMT
date.setSeconds(9);
console.log("Sau:", date.toUTCString()); // Tue, 26 Sep 1989 05:04:09 GMT
Set giây + mili-giây
const date = new Date('1989-09-26T05:04:25.096Z');
date.setSeconds(30, 500);
console.log(date.toUTCString()); // Tue, 26 Sep 1989 05:04:30 GMT (ms=500)
Thiếu giây khi tạo Date
const date = new Date('1989-09-26T04:25'); // Không có giây
date.setSeconds(55);
console.log(date.toISOString()); // 1989-09-26T04:25:55.000Z
Ngày hiện tại set giây
const date = new Date();
date.setSeconds(0, 0); // Đặt về đầu phút
console.log(date.toISOString());
Auto-normalize vượt phạm vi
const date = new Date('1989-09-26T12:00:00');
date.setSeconds(120); // 120s = 2 phút
console.log(date.toISOString()); // 1989-09-26T12:02:00.000Z
date.setSeconds(-30); // Lùi 30 giây
console.log(date.toISOString()); // 1989-09-26T11:59:30.000Z
Lưu ý
- Tham số
secondsbắt buộc,mstùy chọn - Vượt phạm vi tự động normalize (tràn sang phút/giờ/ngày)
- Làm thay đổi object Date gốc
- Khác với
setUTCSeconds()(UTC time) - Cặp đôi với
getSeconds()