5

this is my code:

$(function() {
    $( "#arr_date" ).datepicker({ dateFormat: 'dd-mm-yy' });
    $( "#dep_date" ).datepicker({ dateFormat: 'dd-mm-yy' });
});

$(function() {
    var start = $('#arr_date').val();
    var end = $('#dep_date').val();
    var diff = new Date(end - start);
    var days = diff/1000/60/60/24;
    $('#num_nights').val(days);  
});

I found this date difference solution here on stackoverflow but it doesn't work for me.

It does not calculate the date differences at all. I thought it might be because of the date formatting (dd-mm-yy). I've tried it with yyyy-mm-dd formatting too but it did not work either.

Could anyone help me and tell me what might cause the problem? Thank you.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Peter
  • 135
  • 1
  • 5
  • 13

1 Answers1

21

You don't want to use .val() here, that will give you a string and subtracting strings from each other isn't terribly useful. The datepicker has a method, getDate, that gives you a Date object so you could use that:

var start = $('#arr_date').datepicker('getDate');
var end   = $('#dep_date').datepicker('getDate');
var days   = (end - start)/1000/60/60/24;

Demo: http://jsfiddle.net/ambiguous/TCXcX/

Also, this code:

$(function() {
    var start = $('#arr_date').val();
    var end = $('#dep_date').val();
    var diff = new Date(end - start);
    var days = diff/1000/60/60/24;
    $('#num_nights').val(days);  
});

will run when the DOM is ready but you don't want it to run until the dates have been selected. You'd need to bind your (corrected) calculation code to a button or watch the onSelect events:

function showDays() {
    var start = $('#arr_date').datepicker('getDate');
    var end   = $('#dep_date').datepicker('getDate');
    if(!start || !end)
        return;
    var days = (end - start)/1000/60/60/24;
    $('#num_nights').val(days);  
}

$( "#arr_date" ).datepicker({ dateFormat: 'dd-mm-yy', onSelect: showDays });
$( "#dep_date" ).datepicker({ dateFormat: 'dd-mm-yy', onSelect: showDays });

And another demo: http://jsfiddle.net/ambiguous/5BbGS/

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Thank you. I have done this. My code looks like this: $(function() { var start = $('#arr_date').datepicker('getDate'); var end = $('#dep_date').datepicker('getDate'); var days = (end-start)/1000/60/60/24; $('#num_nights').val(days); }); But still doesn't work. What am I missing? – Peter Dec 10 '11 at 08:58