jquery datepicker + 日期差异计算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8455383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery datepicker + date diff calculation
提问by Peter
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.
我在 stackoverflow 上找到了这个日期差异解决方案,但它对我不起作用。
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.
它根本不计算日期差异。我认为这可能是因为日期格式(dd-mm-yy)。我也用 yyyy-mm-dd 格式尝试过,但它也不起作用。
Could anyone help me and tell me what might cause the problem? Thank you.
谁能帮助我并告诉我可能导致问题的原因?谢谢你。
回答by mu is too short
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:
您不想在.val()这里使用,这会给您一个字符串,并且将字符串彼此相减并不是非常有用。datepicker 有一个方法,getDate,它为您提供一个 Date 对象,以便您可以使用它:
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/
演示: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 onSelectevents:
将在 DOM 准备好时运行,但您不希望它在选择日期之前运行。您需要将(更正的)计算代码绑定到按钮或观看onSelect事件:
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/

