Javascript | Adding days to date string and displaying in specific format

| By Webner

Suppose we want to add a number of days to given date string. For this, it can be done as follows:

var givenDateString = “2016-10-10”;
var dateObj = new Date(givenDateString); // Converting date string to date Object to perform any date operations
var numberOfDaysToAdd = 2;
dateObj.setDate(dateObj.getDate()+ numberOfDaysToAdd); //getDate function is for getting only Date part of given date and setDate is for setting new date and assigning new date to dateObj. Here we are adding 2 days to given date.

Now, we want to return/show date output in required format. For this,

var dateYear = dateObj.getFullYear();
var dateMonth = dateObj.getMonth()+1;   
var dateDay = dateObj.getDate();

In dateMonth variable, we added 1 because getMonth function returns month from 0 to 11. To get correct month, we should always add 1 to given date.

if (dateMonth < 10)
    alert(dateYear + "-0" + dateMonth + "-" + dateDay);
    alert(dateYear + "-" + dateMonth + "-" + dateDay);

In the if condition, we appended 0 to first hyphen so that we get output in format yy-mm-dd i.e. (2016-09-10), not 2016-9-10 if month of given date is less than 10.

Now, we get result 2016-10-12 in alert box.

Leave a Reply

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