How to add months to a date in JavaScript

By Saruque Ahamed Mollick

Hello JavaScript Developer. In this JavaScript tutorial, I am gonna show you how to add months to date in JavaScript. I will give you an easy example so that it becomes easier for you guys to understand.

If you wish you can read these similar tutorials:



How to add seconds to a date object in JavaScript
How to add hours to a JavaScript Date object?

If you want to learn formatting date you can read these,

How to format javascript date to yyyy-mm-dd

 

Those above tutorials are closely related to this one. Almost the same process and the same type of method is used.

Add Months To Date in JavaScript Date Object

Here I have to use two methods:

  • getMonth()
  • setMonth()

Now let’s code it:

<!DOCTYPE html>
<html>
<head>
  <title>Title Goes Here</title>
</head>
<body>
  <script type="text/javascript">
     var mydate = new Date();
     mydate.setMonth(mydate.getMonth()+2);
     document.write(mydate);
  </script>
</body>
</html>

Output:

Thu Jan 10 2019 12:23:15 GMT+0530 (India Standard Time)

In the above example, we added 2 months to the current date object.

var mydate = new Date();

Firstly, This stores the current date in the mydate variable.

 mydate.setMonth(mydate.getMonth()+2);

Then, Here we have added two months to mydate.

Special note: If you wish you can use your custom date. In order to do that just add your own date in the Date() as a parameter.

If you want to use system date just don’t pass any parameter to it.

Finally, I hope this tutorial was helpful to you. Feel free to comment below if any doubt arises.

Leave a Reply

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