jquery datepicker + 日期差异计算 [英] jquery datepicker + date diff calculation

查看:18
本文介绍了jquery datepicker + 日期差异计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

$(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);  
});

我在 stackoverflow 上找到了这个日期差异解决方案,但它对我不起作用.

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

它根本不计算日期差异.我认为这可能是因为日期格式 (dd-mm-yy).我也尝试过使用 yyyy-mm-dd 格式,但它也不起作用.

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.

推荐答案

你不想使用 .val() 在这里,它将为您提供一个字符串,并且将字符串彼此相减并不是非常有用.datepicker 有一个方法,getDate,它给你一个 Date 对象,所以你可以使用它:

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;

演示:http://jsfiddle.net/ambiguous/TCXcX/

另外,这段代码:

$(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);  
});

将在 DOM 准备好时运行,但您不希望它在选择日期之前运行.您需要将(更正的)计算代码绑定到按钮或观看 onSelect 事件:

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 });

另一个演示:http://jsfiddle.net/ambiguous/5BbGS/

这篇关于jquery datepicker + 日期差异计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆