Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีเพิ่มเดือนให้กับ Date ใน JavaScript

ใช้ getMonth() ดึงเดือน (0-11) แล้วบวกจำนวนเดือนที่ต้องการ แล้วตั้งค่ากลับด้วย setMonth() ซึ่งจัดการ year rollover อัตโนมัติ

ตัวอย่างจากบทความ (Basic)

<!DOCTYPE html>
<html>
  <body>
    <script>
      var d, e;
      d = new Date();
      document.write(d);
      e = d.getMonth() + 1; // เพิ่ม 1 เดือน
      document.write("<br>Incremented month = " + e);
    </script>
  </body>
</html>
⚠️ ข้อผิดพลาดในตัวอย่างต้นฉบับ: โค้ดแค่แสดงเดือนที่เพิ่มแล้ว ไม่ได้แก้ไข Date object จริง

วิธีที่ถูกต้อง: ใช้ setMonth()

var date = new Date(); // 2024-01-15
console.log('Original:', date);

// เพิ่ม 3 เดือน
date.setMonth(date.getMonth() + 3);
console.log('After +3 months:', date); // 2024-04-15

// ลด 2 เดือน
date.setMonth(date.getMonth() - 2);
console.log('After -2 months:', date); // 2024-02-15

คุณสมบัติ Auto Rollover

setMonth() จัดการ year boundary อัตโนมัติ:

var date = new Date(2023, 10, 15); // 2023-11-15 (เดือน 10 = พฤศจิกายน)

date.setMonth(date.getMonth() + 3); // +3 เดือน
console.log(date); // 2024-02-15 (ข้ามปีอัตโนมัติ)

date.setMonth(date.getMonth() - 5); // -5 เดือน
console.log(date); // 2023-09-15 (ย้อนปีอัตโนมัติ)

ปัญหา End-of-Month (วันสุดท้ายของเดือน)

var date = new Date(2024, 0, 31); // 2024-01-31
date.setMonth(date.getMonth() + 1); // +1 เดือน
console.log(date); // 2024-03-02 ❌ (ไม่ใช่ 2024-02-29)

// เพราะ กุมภาพันธ์ 2024 มี 29 วัน (leap year) แต่ setMonth พยายามเก็บวันที่ 31
// JS จะ spill over ไปเดือนถัดไป

แก้ไข End-of-Month Issue

function addMonths(date, months) {
  const newDate = new Date(date); // clone
  const day = newDate.getDate();
  
  newDate.setDate(1); // ตั้งเป็นวันที่ 1 ก่อน
  newDate.setMonth(newDate.getMonth() + months);
  
  // ตรวจสอบว่าวันที่เดิมมีในเดือนใหม่หรือไม่
  const lastDayOfNewMonth = new Date(newDate.getFullYear(), newDate.getMonth() + 1, 0).getDate();
  newDate.setDate(Math.min(day, lastDayOfNewMonth));
  
  return newDate;
}

// ทดสอบ
console.log(addMonths(new Date(2024, 0, 31), 1)); // 2024-02-29 ✓
console.log(addMonths(new Date(2024, 0, 31), 2)); // 2024-03-31 ✓
console.log(addMonths(new Date(2023, 0, 31), 1)); // 2023-02-28 ✓ (non-leap)

ใช้ Library (แนะนำสำหรับ Production)

// date-fns
import { addMonths } from 'date-fns';
addMonths(new Date(2024, 0, 31), 1); // 2024-02-29

// dayjs
dayjs('2024-01-31').add(1, 'month').toDate(); // 2024-02-29

// Luxon
DateTime.fromJSDate(new Date(2024, 0, 31)).plus({ months: 1 }).toJSDate();

สรุป

  • ใช้ date.setMonth(date.getMonth() + n) สำหรับกรณีทั่วไป
  • ระวัง end-of-month issue (31 Jan → 2/3 Mar)
  • ใช้ helper function หรือ library (date-fns, dayjs) สำหรับ production