Dùng Date.prototype.setDate() — tự handle rollover tháng/năm.
Thêm prototype method
Date.prototype.addDays = function(days) {
const d = new Date(this.valueOf()); // clone
d.setDate(d.getDate() + days);
return d;
};
const date = new Date();
console.log(date.addDays(1)); // ngày mai
console.log(date.addDays(7)); // 1 tuần sau
console.log(date.addDays(-3)); // 3 ngày trước
Lưu ý
setDatetự xử lý month/year boundary (31/12 + 1 → 1/1 next year).- Mutate original date nếu không clone — nên
new Date(this.valueOf())hoặcnew Date(this.getTime()). - Cho production: cân nhắc
date-fns(addDays),dayjs,luxon— immutable, timezone support, i18n.