Jquery datepicker + diff date calculation

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 solution for the date difference here in stackoverflow, but this does not work for me.

It does not calculate date differences. I thought this might be due to date formatting (dd-mm-yy). I tried it with yyyy-mm-dd formatting, but it didn't work either.

Can someone help me and tell me what might cause the problem? Thanks.

+4
source share
1 answer

You don't want to use .val() here, which will give you a string and subtracting the strings from each other is not terribly useful. Datepicker has a getDate method that gives you a Date object so you can use it:

 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/

In addition, 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 be launched when the DOM is ready, but you do not want it to run until the dates are selected. You will need to bind your (corrected) calculation code to the button or see 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 one more demo: http://jsfiddle.net/ambiguous/5BbGS/

+18
source

Source: https://habr.com/ru/post/1385636/


All Articles