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

Tăng ngày (Increment Date) trong JavaScript không dùng thư viện

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 ý

  • setDate tự 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ặc new Date(this.getTime()).
  • Cho production: cân nhắc date-fns (addDays), dayjs, luxon — immutable, timezone support, i18n.