CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

JavaScript Subtract Days from Date: Save Time with 4 Methods!

Shawpnendu Bikash Maloroy

August 20, 2024
JavaScript Subtract Days from Date - 4 Useful JS Methods
Spread the love

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
    • 1. Using setDate() Method
      • Output:
      • Code Explanation
    • 2. Using getTime() and Milliseconds
      • Output
      • Code Explanation
    • 3. Using 3rd Party JS libraries
      • date-fns Sample Code
      • moment.js Sample Code
    • 4. Using ES6 Arrow Functions and setDate()
      • Output
      • Code Explanation
  • Table: JavaScript subtract days from date methods summary
  • Handling Edge Cases When Subtracting Days
    • Crossing Month Boundaries:
    • Handling Leap Years:
    • Timezone Differences:
    • Daylight Saving Time:
  • Why Would You Subtract Days From a Date?
  • Best Practices for Subtracting Days from a Date
  • Conclusion

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.

Note

If we provide an undefined or NaN equivalent value to the setDate method dateValue parameter, then the setDate() method considers it as an invalid date and returns NaN.

<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:

JavaScript Subtract Days From Date - Using JS Native setDate Method
JavaScript Subtract Days From Date – Using JS Native setDate Method
buymeacoffee

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.

Note

If we provide a number outside the range (for example >31), then the setDate method automatically increases or decreases (for -ve numbers) days and adjusts the month accordingly. But if we provide 0, the setDate() method always provides the last day of the previous month.

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

JavaScript Subtract Days From Date - Considering Milliseconds
JavaScript Subtract Days From Date – Considering Milliseconds

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.

Note

The JS native Date.now() method is a static method of the Date object. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC (coordinated universal time). It is called a Unix timestamp.

buymeacoffee

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

JavaScript Subtract Days From Date - Using ES6 Arrow Functions and setDate()
JavaScript Subtract Days From Date – Using ES6 Arrow Functions and setDate()

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

MethodExample Code SnippetComplexityUse Case
setDate() Methoddate.setDate(date.getDate() - days)SimpleQuick and simple way to subtract days.
Using getTime()new Date(date.getTime() - days * millisecondsPerDay)ModerateIf you need more accurate result.
ES6 Arrow Functionsconst subtractDays = (date, days) => ...ComplexModern, concise syntax with the setDate() method using ES6 syntax.
3rd Party LibrariesDate-fns: subDays(date, days) Moment.js: moment().subtract(days, 'days') See date-fns/ moment.js DocumentationEasyUse 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.

Note

The setDate() method is good for general applications. For precise and more accurate calculation, work with milliseconds. External libraries provide very simple code blocks with additional functionality.

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.

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

🏋️‍♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨‍✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
«Previous
Next»

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    🎮 Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! 🏆
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! 🐶
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!
  • JavaScript No-Code Automation
    JavaScript No-Code Automation: How to Replace Zapier with a Few Lines of Code

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright © 2024 CodersTechZone.com