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

Giảm ngày (decrement date) 1 ngày trong JavaScript


Dùng date.setDate(date.getDate() - 1). Phương thức setDate tự xử lý chuyển tháng/năm (ví dụ 1/3 - 1 ngày = 28/2 hoặc 29/2 năm nhuận).

Ví dụ

Lấy ngày hiện tại, giảm 1 ngày:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Giảm 1 ngày JS</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 20px; font-weight: 500; color: rebeccapurple; }
  </style>
</head>
<body>
  <h1>Giảm ngày 1 ngày trong JavaScript</h1>
  <div class="sample"></div>
  <div class="result"></div>
  <button class="Btn">GIẢM 1 NGÀY</button>
  <h3>Nhấn nút để giảm ngày hiện tại đi 1 ngày</h3>
  <script>
    const resEle = document.querySelector(".result");
    const sampleEle = document.querySelector(".sample");
    const date = new Date();
    sampleEle.textContent = date.toLocaleString('vi-VN');
    document.querySelector(".Btn").addEventListener("click", () => {
      date.setDate(date.getDate() - 1);
      resEle.textContent = `Ngày mới: ${date.toLocaleString('vi-VN')}`;
    });
  </script>
</body>
</html>

Kết quả

Hiển thị ngày hiện tại. Sau khi nhấn, ngày giảm 1 (tự xử lý hết tháng/năm).

Mẹo: Tương tự setDate(getDate() + 1) để tăng ngày. Dùng thư viện date-fns hoặc Luxon cho logic phức tạp.