คำนวณความต่างของวันที่ในเดือนปัจจุบัน
ใช้ new Date().getDate() ดึงวันของเดือนปัจจุบัน และลบกับวันของวันที่ต้องการ
ตัวอย่างโค้ด
var currentDate = new Date().getDate(); // วันปัจจุบัน (1-31)
var subtractDate = new Date("2020-07-01").getDate(); // วันของวันที่กำหนด
const numberOfDaysInCurrentMonthOnly = currentDate - subtractDate;
console.log(numberOfDaysInCurrentMonthOnly); // 27 (ถ้าวันนี้ 28 กรกฎาคม)
วิธีรัน
node fileName.js
ผลลัพธ์ (ตัวอย่างวันที่ 28 กรกฎาคม 2020)
27
⚠️ ข้อจำกัดสำคัญ
- คำนวณเฉพาะ วันในเดือนเดียวกัน ไม่คำนวณข้ามเดือน/ปี
getDate()คืนค่า 1-31 เท่านั้น ไม่รวมเดือน/ปี
วิธีคำนวณความต่างวันที่จริง (รวมข้ามเดือน/ปี)
const date1 = new Date("2020-07-01");
const date2 = new Date(); // วันนี้
const diffTime = Math.abs(date2 - date1); // มิลลิวินาที
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log(diffDays); // จำนวนวันเต็มที่ต่างกัน