To subtract two dates in JavaScript, you can create two Date
objects and then use the getTime()
method to get the time in milliseconds for each date. Then, you can subtract the two-time values and divide them by the number of milliseconds in a day to get the difference in days between the two dates.
JavaScript subtracts dates example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
// Create two Date objects
const date1 = new Date('2023-12-02');
const date2 = new Date('2023-03-30');
// Calculate the difference in time values in milliseconds
const timeDiff = date1.getTime() - date2.getTime();
// Calculate the difference in days
const dayDiff = timeDiff / (1000 * 3600 * 24);
console.log(dayDiff);
</script>
</body>
</html>
Output:
How to subtract days from a date in JavaScript?
Answer: To subtract one day from a date in JavaScript, you can create a new Date
object for the original date and then use the setDate()
method to set the date to the previous day.
// Create a new Date object for the original date
const originalDate = new Date('2023-04-04');
// Subtract one day from the original date
const subtractedDate = new Date(originalDate);
subtractedDate.setDate(originalDate.getDate() - 1);
console.log(subtractedDate); // Output: Sun Apr 03 2023 00:00:00 GMT-0700 (Pacific Daylight Time)
Do comment if you have any doubts or suggestions on this Js date topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version