0

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>
4
  • 1
    In a day, there are 24 hours * 60 minutes * 60 seconds * 1,000 milliseconds = 86,400,000 milliseconds. Commented May 12, 2015 at 14:21
  • Thank you blex - that's helpful Commented May 12, 2015 at 14:25
  • Can you show the relevant html elements? Atleast the reservationStart element would be helpful. Commented May 12, 2015 at 14:34
  • @allanmc added as requested Commented May 12, 2015 at 14:41

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

@allanmic the use of IF to check the validity of the data is a really clever idea that I hadn't considered - thank you. I'm really going to try and use that in my program. .map is taking me awhile to understand and Im try to experiment with your code to show the date in different formats -thanks
Thanks :) Yes the map part is not that easy to understand. It's the same if you did it like this: var dateParts = reservationStart.split('/');. And then just used parseInt(dateParts[x]) the three places in the Date constructor. .
1

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".

2 Comments

I am extremely grateful for the time you took to put this answer together. Your annotations have really helped me to understand some basics of javascript. Thank you
No problem. I toitally understand the frustration when all you can find is stuff that assumes you already know loads.
0

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
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.