Student
Student

Reputation: 55

How to add an arbitary amount of days to any given date in java script

Feel like I am out of my depth here. Moreover, similar questions posted on this site tend to show only a code snippet - not helpful for beginners or keep referring to adding days to today's date, which is not entirely helpful to me either. I have a form which requires the user to enter the Number of days they wish to borrow an item and a date they wish the loan to commence. The latter may be written in the following format 01/12/2015. How do a write a function to get the return date and display it in the form? This is what I have so far

function ReturnDate(){ // code indentation
   var reservationStart = document.getElementById('reservationStart').value;
   var requestedDays = parseInt(document.getElementById('days').value);
   var returnDate = document.getElementById('DateEnd');
   myResult = Date.setTime(reservationStart.getTime() + requestedDays* 86400000);
   DateEnd.value = myResult;
}

Nor am I entirely sure why we multiply by 86400000

As requested, please find the HTML code:

<tr>
    <td>Number of days</td>
    <td><input type="text" name="days" id="days" onkeyup="calculate()" placeholder= "Enter the number of days you wish to borrow the game for" autocomplete="off" style="width:80%" /></td>
</tr>

<tr>
    <td>Date start <i>(dd/mm/yyyy)</i></td>
    <td><input type="text" value="" name="reservationStart" id="reservationStart" onkeyup="ReturnDate()" style="width:80%"/></td>
</tr>

<tr>
    <td>Date end</td>
    <td><input type="text" value="" name="DateEnd" id="DateEnd" style="width:80%"/></td>
</tr>

Upvotes: 0

Views: 66

Answers (3)

allanmc
allanmc

Reputation: 179

Here's a complete example with input validation and Magomogo's date-parsing.

Both input and output is in the format yyyy/mm/dd. If you need to support another format like mm/dd/yyy or dd/mm/yyyy you will have to change those bits.

function ReturnDate() {
    var returnDate = '';
    var reservationStart = document.getElementById('reservationStart').value;
    var requestedDays = parseInt(document.getElementById('days').value);
    var dateEnd = document.getElementById('DateEnd');
    var dateParts = reservationStart.split('/').map(function(i) {
        return parseInt(i);
    });
    // Check that input is valid, otherwise ignore
    if (dateParts.length == 3 && !isNaN(requestedDays) ) {
        var d = new Date(
            dateParts[0],
            dateParts[1] - 1,
            dateParts[2] + requestedDays
        );
        // If the date is valid, return it, otherwise return error.
        if (!isNaN(d.getTime())) {
            returnDate = d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate();
        } else {
            returnDate = '?';
        }
    }
    DateEnd.value = returnDate;
}
<table>
  <tr>
      <td>Number of days</td>
      <td><input type="text" name="days" id="days" onkeyup="ReturnDate()" /></td>
  </tr>

  <tr>
      <td>Date start <i>(yyyy/mm/dd)</i></td>
      <td><input type="text" value="" name="reservationStart" id="reservationStart" onkeyup="ReturnDate()" /></td>
  </tr>

  <tr>
      <td>Date end <i>(yyyy/mm/dd)</i></td>
      <td><input type="text" value="" name="DateEnd" id="DateEnd" /></td>
  </tr>
</table>

Upvotes: 2

user2808054
user2808054

Reputation: 1386

See this working JSFiddle :

Date adjust & format

Here's the code ..

function ReturnDate(){ // code indentation
   var reservationStart = document.getElementById('reservationStart').value;
   var requestedDays = parseInt(document.getElementById('days').value);
   var returnDate = document.getElementById('DateEnd');
   //myResult = Date.setTime(reservationStart.getTime() + requestedDays* 86400000);
   var arrParts = reservationStart.split("/"); // aray of date parts
   // params are year, month, day, hour, min, second, millisecond (all numeric)
   // Months are 0-based (jan = 0) so subtract 1 on second parameter
    // add the days requested to the 3rd parameter to amend the date.
   var myDate = new Date(arrParts[0], parseInt(arrParts[1])-1, parseInt(arrParts[2]) + requestedDays, 0, 0, 0, 0);

   // now build a string out of it
   var sResult = myDate.getFullYear()+"/";
   sResult += ("0"+(myDate.getMonth()+1)).substr(-2)+"/";
   sResult += ("0"+myDate.getDate()).substr(-2);
   document.getElementById('DateEnd').value =   sResult;
}

The crux of it is adding requestedDays to the days part of the date object.

Hopefully the comments explain what's going on. the bit about adding "0" to the start of the strings at the end is to cater for single digit months and days eg march = "03".

Upvotes: 1

Magomogo
Magomogo

Reputation: 954

Difference between days is not always 24 hours. Because of daylight saving time it can be 23 or 25 hours. So it's not accurate to just add 86400 seconds to get to the next day.

I'd recommend to use Date constructor to get accurate result:

var dateParts = reservationStart.split('/')
    .map(function (i) { return parseInt(i); });

var dateEnd = new Date(
    dateParts[0], 
    dateParts[1] - 1, 
    dateParts[2] + requestedDays
);

Upvotes: 0

Related Questions