我正在尝试使用jquery datepicker计算所选#from day和#to day之间的总天数
"在写这篇文章之前我已经阅读了很多问题所以我只是想问为什么下面的代码不起作用。"
这是代码:
$(function() {
$( "#from" ).datepicker({
numberOfMonths: 1,
minDate:0,
dateFormat: 'dd-mm-yy',
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
$("input[name='to']").val(selectedDate);
var dayFrom = selectedDate; /* Selected From Date */
}
});
$( "#to" ).datepicker({
defaultDate: "+1w",
numberOfMonths: 1,
minDate:0,
dateFormat: 'dd-mm-yy',
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
var dayTo = selectedDate; /* Selected To Date */
$(dayFrom, dayTo).change(function(){
if($(dayFrom).val() && $(dayTo).val()){
var startDate = parseDate($(dayFrom).val());
var endDate = parseDate($(dayTo).val());
var days = calcDaysBetween(startDate, endDate);
var price = calcPrice(days);
$('#finalDagen').html(days);
}
});
function parseDate(s){
var parts = s.split('/');
return new Date(parts[2], parts[0]-1, parts[1]);
}
function calcDaysBetween(startDate, endDate){
return (endDate-startDate)/(1000*60*60*24);
}
}
});
});
答案 0 :(得分:0)
观察
onClose
方法应该是
jQuery(function ($) {
var $from = $("#from"),
$to = $("#to");
$from.datepicker({
numberOfMonths: 1,
minDate: 0,
dateFormat: 'dd-mm-yy',
onClose: function (selectedDate) {
$to.datepicker("option", "minDate", selectedDate);
}
});
$to.datepicker({
defaultDate: "+1w",
numberOfMonths: 1,
minDate: 0,
dateFormat: 'dd-mm-yy',
onClose: function (selectedDate) {
$from.datepicker("option", "maxDate", selectedDate);
}
});
$from.add($to).change(function () {
var dayFrom = $from.datepicker('getDate');
var dayTo = $to.datepicker('getDate');
if (dayFrom && dayTo) {
var days = calcDaysBetween(dayFrom, dayTo);
$('#finalDagen').html(days);
}
});
function calcDaysBetween(startDate, endDate) {
return (endDate - startDate) / (1000 * 60 * 60 * 24);
}
});
演示:Fiddle
答案 1 :(得分:-1)
尝试减去两个:
var dayDifference = dayTo - dayFrom;