To subtract days from a date, we can use the JavaScript getTime() method. The getTime() method converts dates into the number of milliseconds since January 1st, 1970. Since there are 86400000 milliseconds in 1 day, we can subtract multiples of 86400000 to our converted date to subtract as many days as we want.
var date1 = new Date();
var dateToMilliseconds = date1.getTime();
var subtractedDays = dateToMilliseconds + (86400000*5);
//This will subtract 5 days to our date.
var newDate = new Date(subtractedDays);
//This will create a new date that will be 5 days prior the current date
We can also add milliseconds to add days to a date. Below are some examples of subtracting days from a date object with the help of the getTime() method.
var date1 = new Date();
var dateToMilliseconds = date1.getTime();
var result1 = date1;
var result2 = new Date(dateToMilliseconds+(-86400000*5));
var result3 = new Date(dateToMilliseconds+(-86400000*7));
var result4 = new Date(dateToMilliseconds+(-86400000*30));
var result5 = new Date(dateToMilliseconds+(86400000*5));
Which would result in the following:
result2 = Wed Jan 26 2022 12:11:53 GMT-0500 (Eastern Standard Time);
result3 = Mon Jan 24 2022 12:11:53 GMT-0500 (Eastern Standard Time);
result4 = Sat Jan 01 2022 12:11:53 GMT-0500 (Eastern Standard Time);
result5 = Sat Feb 05 2022 12:11:53 GMT-0500 (Eastern Standard Time);
Subtract Days from a Date Using JavaScript with a Click
In this example, we will let the user subtract days from the current date using an input field. We will use the JavaScript getTime() method to convert dates to milliseconds like we did above.
Here is our HTML setup:
How many days do you want to subtract from the current date and time?
Below is the JavaScript code which will take the user input using the onclick event and run the function below. The function will subtract the days from the current date like we did above. We will then update the #results div using the textContent property.
function subtractDays() {
var date1 = new Date();
var dateToMilliseconds = date1.getTime();
var userDays = document.getElementById("userVal").value;
var subtractedDays = dateToMilliseconds + (-86400000*userDays);
var newDate = new Date(subtractedDays);
document.getElementById("results").textContent = newDate;
}
The final code and output for this example is below:
Code Output:
How many days do you want to subtract from the current date and time?
Full Code:
How many days do you want to subtract from the current date and time?
<script>
function subtractDays() {
var date1 = new Date();
var dateToMilliseconds = date1.getTime();
var userDays = document.getElementById("userVal").value;
var subtractedDays = dateToMilliseconds + (-86400000*userDays);
var newDate = new Date(subtractedDays);
document.getElementById("results").textContent = newDate;
}
</script>
Hopefully this article has been useful in helping you understand how to use JavaScript to subtract days from a date.