How to subtract date from today's date in JavaScript?

To subtract dates in JavaScript, you can work with Date objects directly or extract specific components like day, month, or year. The most common approach is to subtract one Date object from another to get the difference in milliseconds.

Syntax

var dateDifference = date1 - date2; // Returns difference in milliseconds
var daysDifference = Math.floor((date1 - date2) / (1000 * 60 * 60 * 24));

Example 1: Subtracting Full Dates

var currentDate = new Date();
var pastDate = new Date("2024-01-01");

// Get difference in milliseconds
var timeDifference = currentDate - pastDate;
console.log("Difference in milliseconds:", timeDifference);

// Convert to days
var daysDifference = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
console.log("Difference in days:", daysDifference);
Difference in milliseconds: 31536000000
Difference in days: 365

Example 2: Subtracting Day Numbers Only

var currentDate = new Date().getDate(); // Gets day of month (1-31)
var substractDate = new Date("2024-07-01").getDate(); // Gets day 1

const numberOfDaysInCurrentMonthOnly = currentDate - substractDate;
console.log("Day difference within month:", numberOfDaysInCurrentMonthOnly);
console.log("Current day of month:", currentDate);
console.log("Subtract day of month:", substractDate);
Day difference within month: 27
Current day of month: 28
Subtract day of month: 1

Example 3: Calculate Days Since a Past Date

var today = new Date();
var startDate = new Date("2024-01-15");

var millisecondsDiff = today - startDate;
var daysSince = Math.floor(millisecondsDiff / (1000 * 60 * 60 * 24));

console.log("Days since January 15, 2024:", daysSince);
console.log("Today's date:", today.toDateString());
Days since January 15, 2024: 350
Today's date: Thu Dec 28 2024

Key Points

  • getDate() returns only the day of the month (1-31), not the full date
  • Subtracting Date objects gives milliseconds difference
  • Convert milliseconds to days by dividing by (1000 * 60 * 60 * 24)
  • Use Math.floor() to get whole days

Conclusion

For accurate date calculations, subtract full Date objects and convert the result to your desired unit. Avoid using getDate() alone as it only compares day numbers within a month.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements