How can I compare date/time values using the jQueryUI datepicker and HTML5 time input?

和自甴很熟 提交于 2019-12-02 05:01:41

问题


I want to validate that the "begin" date/time pair predates the "end" date/time pair on a page. I'm using the jQueryUI datepicker, and the HTML5 time input element/widget.

This jQuery:

    var begD = $.datepicker.parseDate('mm/dd/yy', $('#BeginDate').val());
    var endD = $.datepicker.parseDate('mm/dd/yy', $('#EndDate').val());
    if (begD > endD) {
            alert('Begin date must be before End date');
            $('#BeginDate').focus();
            return false;
    }    

(see this script in context here: http://jsfiddle.net/clayshannon/QCrXG/9/)

...works for comparing the datepicker vals, but I need to incorporate the time elements too, so that a time (on the same date) that is earlier in the "End" time element than the "Begin" time element will also flag the range as invalid.

How to do that?


回答1:


Here's an approach. You need to test to see if the dates are the same, and then inside that, append the times to new date objects that you can then compare. (There might be a faster way to do this, but this works in testing, here: http://jsfiddle.net/mori57/SEqVE/):

} else if(begD.toString() == endD.toString() ){
    var dteString = begD.getFullYear() + "/" + (begD.getMonth()+1) + "/" + begD.getDate();
    var begT = new Date(dteString + " " + $('#BeginTime').val());
    var endT = new Date(dteString + " " + $('#EndTime').val());

    if( begT > endT ){
        alert('Begin date must be before End date');
        $('#BeginTime').focus();
        return false;
    }
}


来源:https://stackoverflow.com/questions/18192288/how-can-i-compare-date-time-values-using-the-jqueryui-datepicker-and-html5-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!