Adding days to date type in Javascript - Another solution

Author - Webner
6.03.2020
|
0 Comments
||

I have already written a blog on this topic. Please refer to the following link for detail: Click This Link

Introduction

I will show another solution to add a number of days to a date string. The solution provided in the above link works well and gives an expected result. But, recently I faced a problem with the above solution. I have selected the date from datepicker and the format of the date selected from datepicker is unknown on client-side script to which we have to add a number of days and the solution provided in the above link gives an unexpected result. You can use both solutions:

  • The solution provided in the above link
  • The new solution which I will give in this blog.

Let’s see how we can add the number of days to the date in another way:


var dateObj = new Date(dateSelected); // dateSelected is the date to which we will add a number of days. It can be a date string or date selected from any datepicker in any format.

var numberOfDaysToAdd = 30;

var newDateVal = new Date(dateObj.getTime() + (numberOfDaysToAdd*24*60*60*1000));
// Here instead of setDate() function in the above link, we are using the getTime() function and adding milliseconds to it. Rest all code is the same.
var dateYear = newDateVal.getFullYear();
var dateMonth = newDateVal.getMonth()+1;
var dateDay = newDateVal.getDate();
if (dateMonth < 10) dateMonth = "0"+dateMonth; if(dateDay < 10) dateDay = "0"+dateDay; newDate = dateMonth + "/" + dateDay + "/" + dateYear; // Date format in mm/dd/yy alert(newDate); newDate = dateYear + "-" + dateMonth + "-" + dateDay; // Date format in yy-mm-dd alert(newDate);

If you face a problem with the solution provided in the link mentioned (previous blog) with setDate() function, you can choose a new solution mentioned in this blog and can show the result in any format. Otherwise, you can choose any of the solutions you are comfortable with.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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