0

I have read a few articles but nothing seems to the point. I have created a form that records a reservation date (when a user wants to reserve a game) and the number of days they hope to borrow it for. I want to add this to the reservation date to get the date the game must be returned by. I have wrapped up my code so far into a function so that I can call it using an onclick method. What should this code look like to work properly? Almost forgot - to make life hard my date is written like this YYYY-MM-DD

    function ReturnDate(){
    var reservation_begin = document.getElementById('reservation_start').value;
    var loan_period = document.getElementById('requested_days').value;
    var reservation_end = document.getElementById('return_date');
    var dateResult = reservation_begin + loan_period;
    return_date.value = dateResult;
}

USING the Suggestions made by Linus I made the following alterations but had trouble with the formatting of the return date. e.g Setting the reservation date to 2015-01-03 gave me the result of 2015-0-32 for the return date

function ReturnDate(){
    var reservation_begin = document.getElementById('reservation_start').value;
    var loan_period = document.getElementById('requested_days').value;
    var resDate = new Date(reservation_begin);
    alert(resDate)
    var period = loan_period;
    var output = document.getElementById('return_date');

    resDate.setDate(resDate.getDate() + period);
    alert(period)
    //return_date.value = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
    return_date.value = resDate.getFullYear() + "-" + resDate.getMonth() + "-" + (resDate.getDate() +1);
}
7
  • 1
    JavaScript dates are a bit tricky - you may want to use something like moment.js instead. Commented Jan 30, 2015 at 10:15
  • NB I have tried adding this return_date.value = Date.today(reservation_begin).add(loan_period).days(); instead of "return_date.value =...." with no luck Commented Jan 30, 2015 at 10:16
  • 1
    Are you already using a library? Where did you get Date.today( from? Commented Jan 30, 2015 at 10:19
  • No - sorry - my previous code simply added the number onto the date so 2015-01-03 became 2015-01-031. I just thought that I needed to tell java script that I am playing around with dates. The extra code had not syntax errors but failed to work Commented Jan 30, 2015 at 10:31
  • 1
    Split reservation_begin and use the Date constructor feeding in the parts to create a Javascript date object. getTime will give you the milliseconds since the Epoch. There are 86400000 seconds in a day, so multiple this by loan_period. Add the two millisecond result together and use the Date constructor with your total milliseconds to get dateResult as a Javascript date object. Commented Jan 30, 2015 at 10:31

4 Answers 4

2

As mentioned dates could be a bit tricky to handle with js. But to just add days to a date this could be a solution?

JSBIN: http://jsbin.com/lebonababi/1/edit?js,output

JS:

var resDate = new Date('2015-02-01');
var period = 6;
var output = "";

resDate.setDate(resDate.getDate() + period);
output = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();

alert(output);

EDIT:

Added a new JSBin which is more consistent with the original code.

JSBin: http://jsbin.com/guguzoxuyi/1/edit?js,output

HTML:

  <input id="reservationStart" type="text" value="2015-03-01" />
  <br />
  <input id="requestedDays" type="text" value="14" /> 
  <br />
  <a id="calculateDate" href="javascript:;">Calculate Date</a>

  <br /><br /><br />  

  Output:
  <input id="calculatedDate" type="text" />

JS:

// Click event
document.getElementById('calculateDate').addEventListener('click', returnDate);

// Click function
function returnDate(){

  var reservationStart = document.getElementById('reservationStart').value,
      requestedDays = parseInt(document.getElementById('requestedDays').value),
      targetDate = new Date(reservationStart),
      formattedDate = "";


  // Calculate date
  targetDate.setDate(targetDate.getDate() + requestedDays);

  // Format date
  formattedDate = formatDate(targetDate);

  // Output date
  document.getElementById('calculatedDate').value = formattedDate;

}

// Format date (XXXX-XX-XX)
function formatDate(fullDate) {

  var dateYear = fullDate.getFullYear(),
      dateMonth = fullDate.getMonth()+1,
      dateDays = fullDate.getDate();

  // Pad month and days
  dateMonth = pad(dateMonth);
  dateDays = pad(dateDays);  

  return dateYear + "-" + dateMonth + "-" + dateDays;

}

// Pad number
function pad(num) {

  return (num < 10 ? '0' : '') + num;

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

3 Comments

I like the simplicity of this.
I gave this a good go and used the alert() to try and trouble shoot. Setting the reservation date to 2015-01-03 gave me the result of 2015-0-32. I am currently experimenting with the output line to see if I can change the formatting
@Linus Sorry for the delay - had to do other stuff. Really excited by this script. It seems to do everything I want and 95% seems to make great sense to me (I'am working on the other 5% now).Thank you so much. Everyone here has been so helpful and as a beginner, its what you need to make progress.
1

As per my comment,

Split reservation_begin and use the Date constructor feeding in the parts to create a Javascript date object. getTime will give you the milliseconds since the Epoch. There are 86400000 milliseconds in a day, so multiply this by loan_period. Add the two millisecond result together and use the Date constructor with your total milliseconds to get dateResult as a Javascript date object.

using Date.UTC but you don't have to.

function pad(num) {
    return num < 10 ? '0' + num : num;
}

var reservation_begin = ('2015-02-01').split('-'),
    loan_period = '5',
    begin,
    end;

reservation_begin[1] -= 1;
begin = new Date(Date.UTC.apply(null, reservation_begin)).getTime();
end = new Date(begin + 86400000 * loan_period);
document.body.textContent = [
    end.getUTCFullYear(),
    pad(end.getUTCMonth() + 1),
    pad(end.getUTCDate())
].join('-');

Why split the date string into parts? This is to avoid cross browser parsing issues.

Why use milliseconds? This is the smallest value represented by Javascript Date, using this will avoid any rollover issues that may be present in browsers.

Why use UTC? You haven't specified the requirements for your script, and this is about as complex as it gets. You don't have to use it, you can just feed the parts into Date and use the non UTC get methods.

What does pad do? It formats the month values to MM and date values to DD.

Note that month is zero referenced in Javascript so months are represent by the numbers 0-11.

1 Comment

Thank you so much for taking the time to write code and explaining it to me. I am extremely grateful with your patience. I will experiment with this and let you know if I can get it to work. Then vote
1

A bit confused with the third variable "reservation_end" but according to your question this solution might work. var dateResult = new Date(reservation_begin); dateResult.setDate(dateResult.getDate() + parseInt(loan_period)); alert(dateResult);

http://jsfiddle.net/uwfpbzt2/

Comments

1

Example using todays date:

var today = new Date();
today.setDate(today.getDate() + x);

where x is the number of days. Then just use getYear(), getMonth() and getDate() and format it how you like.

EDIT

var myDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);

Assuming your date is entered in dd/mm/yyyy format as inputDate then

dateParts = inputDate.split("/");
var myDate = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);

Depending on the date format your split() delimiter and array positions may be different but this is the general idea.

4 Comments

This looks really encouraging, but the difficulty I am having is substituting today's date with the one recorded in my form (reservation start) and X with loan period. Please could you help - I'm a real beginner here.
Updated my answer with some extra info
Don't forget that months are 0 referenced. dateParts[1] - 1 and same getMonth() + 1 when displaying.
Thanks @Xotic750. Friday afternoon error now corrected. Serves me right for not testing :-)

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.