how to subtract days from a date in javascript

By Saruque Ahamed Mollick

In this JavaScript tutorial, I will show you how to subtract days from a date in JavaScript very easily with JavaScript inbuild method. In my previous post, I have explained and shown you How to compare two dates in JavaScript. You can also check that out if you want.

Now in this post, we gonna learn how to subtract days from a date in JavaScript. We don’t need to be a JavaScript hero to do this. Just two lines of code and that’s all. But you need to know what is going on behind this all.

To learn this, you need to know the following and you are done

  • Date()
  • setDate()
  • getDate()

Free cool 3d image hover effect source code download



Subtract days from a date in JavaScript

Just create a date variable. Set the value of the date to any previous date you want by subtracting the number of days you wanna go back.

At first, I am gonna show you subtracting days from the current date. Later I’ll show you how to subtract days from any date you want in JavaScript.

<!DOCTYPE html>
<html>
<head>
  <title>Title Goes Here</title>
</head>
<body>
  <script type="text/javascript">
     var date1 = new Date();
     date1.setDate(date1.getDate()-5);
     document.write(date1);
  </script>
</body>
</html>

Output:

Sat Oct 13 2018 11:14:09 GMT+0530 (India Standard Time)

This will print the date we had 5 days ago.

Now let just take any date we want then subtract.

 var date1 = new Date('2018-05-26');
 date1.setDate(date1.getDate()-5);
 document.write(date1);

Output:

Mon May 21 2018 05:30:00 GMT+0530 (India Standard Time)

Don’t worry about the time zone. It will take the zone from your system.

date1.setDate(date1.getDate()-n);

n is the value of days which you wanna deduct or subtract from your given date. ( or system date, in case you did not put anything in the Date() )

You may also be interested in,

Calculate the difference between two dates in PHP

How To Change Background Color Every Seconds in JavaScript

2 responses to “how to subtract days from a date in javascript”

  1. Fattah says:

    how to i Subtract the date to 6 month before? any idea?

  2. Saruque Ahamed Mollick says:

    Your question is not cleared.
    But if you want to subtract 6 months ( 6×30=180 days ) then just use date1.setDate(date1.getDate()-180);
    Or if you wish to subtract days from the date of 6 months ago then fetch the date of 6 months ago first. Thereafter simply use that day in the Date() object. Then proceed the above program given in this tutorial

Leave a Reply

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