Badger
Badger

Reputation: 166

Calculating dates in Javascript returns NaN-NaN-NaN

I'm currently working a small application which incorporates a date calculation in javascript. It consists of 3 form elements. The first element lets a user specify the number of nights he would like to stay. The second element specifies the start date and the third element specifies the end date. Once the user chooses the staying length, the amount of nights should be added to the start date.

This is what I've come up with in Javascript for the "end_date" calculation:

function setExpDate(formDate){
// set number of days to add
var daystoadd2 = getStayingLength();
var startDate = new Date(formDate);

var expDate = startDate;
expDate.setDate(startDate.getDate() + daystoadd2);


var totaldate = expDate;
var curr_date = expDate.getDate();
var curr_month = expDate.getMonth() +1;
var curr_year = expDate.getFullYear();
var totaldate = (curr_date + "-" + curr_month + "-" + curr_year);

document.getElementById('end_Date').value = totaldate;};

This function is triggered with the onBlur event on the start_date field. This results in NaN-NaN-NaN. How should I change my code to make this work?

You can find the "app" here: Form Calculation

Upvotes: 0

Views: 3862

Answers (1)

Anto Jurković
Anto Jurković

Reputation: 11258

Your function setDate() worked with the following formats (because that is how Date() works):

setExpDate('11/29/2013');
setExpDate('November 29, 2013');
setExpDate('2013-11-29');
setExpDate('Friday November 29 2013');

If you want to use some other format as input, like 19-12-2013 then you have to change it before calling Date(). One possible way:

var dateParts = formDate.split('-');
formDate = dateParts[1] + '/' + dateParts[0] + '/' + dateParts[2];
var startDate = new Date(formDate);

Upvotes: 1

Related Questions