-1

I have a function that gets a date from a jQuery calendar and then formats it in year-month-day.

The date I get for the calendar is 03/04/2013 for dateString and then I want it in the format of 2013-03-04. But the date I am getting for start_date is 2013-21-04. Strange because it had been ok, I think.

function makeUpDates() {
    // concantenate values to date_start and date_end hidden inputs
    var dateString = document.getElementById('date').value, date = new Date(dateString);
    document.getElementById('date_start').value = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + ("0" + date.getDate()).slice(-2);
    var numDays = document.getElementById('slider').value;
    date.setDate(date.getDate() + parseInt(numDays));
    var dateEnd = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + ("0" + date.getDate()).slice(-2);
    document.getElementById('date_end').value = dateEnd;
}
j08691
  • 197,815
  • 30
  • 248
  • 265
Keith Power
  • 13,207
  • 19
  • 62
  • 123

2 Answers2

1

You can convert the dates like this

//will take a date in the form MM/DD/YYYY and return YYYY-MM-DD
function convertDate(dateString){
    var dateparts = dateString.split("/");
    var newDate = dateparts[2]+"-"+dateparts[0]+"-"+dateparts[1]
    return newDate;
}

Also for more general Date handling you can check out moment.js, mentioned in this answer to a more general question on this topic

Community
  • 1
  • 1
Ben McCormick
  • 24,338
  • 12
  • 50
  • 71
1

start_date is 2013-21-04

Probably you forgot the parenthesis around date.getMonth()+1 in the string concatenation, yielding 21 instead of 3. It seems to be fixed in the snippet you posted though.

Bergi
  • 572,313
  • 128
  • 898
  • 1,281