Để cộng ngày, dùng Date() lấy ngày hiện tại rồi cộng milliseconds tương ứng (ngày * 24 * 60 * 60 * 1000).
Ví dụ: Cộng 2 ngày
<!DOCTYPE html>
<html>
<body>
<script>
var date = new Date();
document.write(date); // Current date
// Cộng 2 ngày: 2 * 24 * 60 * 60 * 1000 ms
var incDate = new Date(new Date().getTime() + (2 * 24 * 60 * 60 * 1000));
document.write("<br>" + incDate);
</script>
</body>
</html>
Hàm tiện ích reusable
function addDays(date, days) {
const result = new Date(date); // Clone để không mutate original
result.setDate(result.getDate() + days);
return result;
}
// Usage
const today = new Date();
console.log(addDays(today, 2)); // 2 ngày sau
console.log(addDays(today, -5)); // 5 ngày trước
console.log(addDays(today, 30)); // 1 tháng sau (tự xử lý month/year rollover)
Tại sao dùng setDate() thay vì cộng milliseconds?
setDate()tự xử lý month/year rollover (31/12 + 1 = 1/1 năm sau).- Xử lý DST (Daylight Saving Time) đúng hơn (milliseconds có thể sai 1 giờ).
- Code đọc hiểu dễ hơn.
Thư viện khuyên dùng
- date-fns:
addDays(date, 2)- lightweight, modular, functional. - Luxon:
DateTime.now().plus({days: 2})- immutable, timezone support tốt. - Day.js:
dayjs().add(2, 'day')- API giống Moment.js nhưng nhẹ (2KB). - Temporal API (ES proposal Stage 3):
Temporal.PlainDate.from(date).add({days: 2})- tương lai chuẩn JS.
Lưu ý
new Date().getTime() trả về milliseconds từ epoch (UTC). setDate() làm việc với local time components. Chọn cách phù hợp ngữ cảnh (UTC vs local).