As a JavaScript developer, we have to work with dates. JavaScript subtract days from date manipulation is almost a daily job for us. There are so many cases where you need to subtract days from the date, such as historical data representation, report generation, data filtering, log processing, etc.
In this post, I will discuss the most common, simple, and effective ways to subtract days from a date in JavaScript. From native JavaScript methods to third-party libraries, I will cover everything with code examples and explanations. Therefore, bear with me till the end. You are going to get a proper JS method on how JavaScript subtract days from date.
Table of Contents
Methods to Implement JavaScript Subtract Days from Date
Let’s discuss the most common and simple native JS methods to subtract days from a date in JavaScript:
1. Using setDate() Method
One of the most popular ways to subtract days from a date in JavaScript is using the setDate() method. This method allows us to change the day directly of the month in a Date object.
<script>
function subtractDays(date, days) {
const result = new Date(date);
// Dont use setDate(days).
// Because this will directly set the day to 5th of the month.
// Example: lets say today is 20th Aug. And you want to subtract 5 days.
// Then you will get 5th August not 15th August.
// So Always subtract your number from day of the month.
// If you want to advance a date then add.
result.setDate(result.getDate() - days);
return result;
}
const currentDate = new Date();
// javascript subtract days from date
var newDate = subtractDays(currentDate, 5);
var newDate2 = subtractDays(currentDate, 22);
console.log('Subtract 5 Days: '+newDate);
// output: Aug 15
// Todays date is 20th August
console.log('Subtract 22 Days: '+newDate2);
// output: Jul 29
</script>
Output:
Code Explanation
The JS setDate() method subtracts the provided number of days (here 5 and 22) by adjusting the day of the month (20th Aug). The result is a new date with the days subtracted. The getDate() method always return day of the month using local time.
Now you have implemented JavaScript subtract Days from Date method using setDate(). You may need a guideline on JS date time formatting. For that, you can follow the MDN documentation.
2. Using getTime() and Milliseconds
In my second code example, I am going to explain how we can use the JS native getTime() method to subtract days from a date. Please note that JS stores date as the number of milliseconds since January 1, 1970. So it’s simple to subtract the number of milliseconds. The number of milliseconds of a day is (Hours * Minutes * Seconds * Milliseconds) 24 * 60 * 60 * 1000 = 86,400,000 ms.
<script>
function subtractDaysUsingMilliseconds(date, days) {
// Hours * Minutes * Seconds * Milliseconds
const millisecondsPerDay = 24 * 60 * 60 * 1000;
// If you want days addition then use +
const result = new Date(date.getTime() - days * millisecondsPerDay);
return result;
}
// current date is Aug 20, 2024
const currentDate = new Date();
const newDate1 = subtractDaysUsingMilliseconds(currentDate, 7);
const newDate2 = subtractDaysUsingMilliseconds(currentDate, 22);
// javascript subtract days from date
console.log("-7 Days: "+newDate1);
console.log("-22 Days: "+newDate2);
</script>
Output
Code Explanation
The method simply worked by calculating the total milliseconds of a day and multiplying it with the number of days that you want to subtract. Then subtracting this newly calculated miliseconds from the timestamp of the provided date.
3. Using 3rd Party JS libraries
You can use date-fns subDays() for subtracting days from a date. Another popular library is moment.js. Use .subtract() method to subtract dates in easy ways. It’s recommended to follow the provider’s website.
date-fns Sample Code
const { subDays } = require('date-fns');
const currentDate = new Date();
const newDate = subDays(currentDate, 10);
console.log(newDate);
moment.js Sample Code
const moment = require('moment');
const currentDate = moment();
const newDate = currentDate.subtract(3, 'days');
console.log(newDate.format('YYYY-MM-DD'));
4. Using ES6 Arrow Functions and setDate()
If you are familiar with ES6 syntax, then it’s recommended to use ES6 syntax. Using this, you can create a more concise setDate() method with arrow functions.
<script>
// Recommended method of javascript subtract days from date
const subtractDaysES6 = (date, days) => {
const result = new Date(date);
result.setDate(result.getDate() - days);
return result;
}
const currentDate = new Date();
// javascript subtract days from date
// Consider today is 20th Aug, 2024
// Now subtract 15 and 22 days
console.log("-15 Days: " + subtractDaysES6(currentDate, 15));
console.log("-22 Days: "+ subtractDaysES6(currentDate, 22));
</script>
Output
Code Explanation
This arrow function is very similar to my first example, with one exception only. Here I use modern JavaScript syntax to generate cleaner and more concise code. Thus, I am recommending it.
Table: JavaScript subtract days from date methods summary
Method | Example Code Snippet | Complexity | Use Case |
setDate() Method | date.setDate(date.getDate() - days) | Simple | Quick and simple way to subtract days. |
Using getTime() | new Date(date.getTime() - days * millisecondsPerDay) | Moderate | If you need more accurate result. |
ES6 Arrow Functions | const subtractDays = (date, days) => ... | Complex | Modern, concise syntax with the setDate() method using ES6 syntax. |
3rd Party Libraries | Date-fns: subDays(date, days) Moment.js: moment().subtract(days, 'days') See date-fns/ moment.js Documentation | Easy | Use for enterprise level projects. |
Handling Edge Cases When Subtracting Days
When subtracting days from a date, we have to consider some edge cases that may arise. Few of them are:
Crossing Month Boundaries:
I have already discussed this issue in my earlier examples. However, I am again mentioning this issue so that you don’t forget. Sample code based on my #1 example subtractDays() method:
const currentDate = new Date('2024-03-01');
const newDate = subtractDays(currentDate, 5);
console.log(newDate); // Outputs: 2024-02-25
Handling Leap Years:
JavaScript automatically handles leap years during performing date addition or subtraction. You don’t need to take care of it. One more code example based on my #1 example subtractDays() method to try:
const leapYearDate = new Date('2024-02-29');
const newDate = subtractDays(leapYearDate, 1);
console.log(newDate); // Outputs: 2024-02-28
Timezone Differences:
In case of processing or presenting server-side and client-side dates, it’s highly recommended to write your code cautiously and test it before deployment. Make sure that time zone is considered while developing applications for different regions.
Daylight Saving Time:
DST can affect date calculations, depending on the region. So consider it also.
Why Would You Subtract Days From a Date?
You need to subtract days from a date using JavaScript for several reasons. Some of the reasons are:
- To calculate past due dates
- For countdown timers
- Adjusting for business logic like subtracting weekends or holidays
- Historical data analysis
- Log or data filtration by date range
Best Practices for Subtracting Days from a Date
Please follow the below best practices when subtracting days from a date in JavaScript:
- Use Built-in Methods: The native JavaScript methods like setDate() are often sufficient for simple date manipulation tasks. These methods are fast and reliable.
- Enterprise Level Application Development: For complex date calculations or if you are dealing with different time zones or international dates, consider using 3rd party libraries like date-fns or moment.js.
- Handle Edge Cases: Consider boundary issues like month boundaries, leap years, and timezone differences, and ensure your code handles these properly.
- Test Your Code with Various Dates: Always test your date calculations with various inputs, such as the end of the month, leap years, and daylight saving time shifts.
Conclusion
Javascript subtract days from date Operations are straightforward, but you have to give your high-level attention. Based on your project, choose the right method from using simple built-in methods to external libraries for enterprise solutions.
Whether you are working with deadlines, scheduling tasks, or analyzing historical data, understanding how to subtract days from a date in JavaScript is very important.
I hope that by keeping my guidelines on “JavaScript subtract days from date” in mind, you will be able to handle complex date calculations in your future JavaScript projects.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply