6

这里的代码

$(document).ready(function() {
    $('#st').change(function(){
        var st = $('#st').val(); // start time Format: '9:00 PM'
        var et = $('#et').val(); // end time   Format: '11:00 AM' 

        //how do i compare time
            if(st > et)
            {
               alert('end time always greater then start time');
            }
    });
});

如果我的时间范围如下

Start Time Range (listbox) =   12:00 AM To 11:59PM

End Time Range  (listbox)  =   12:00 AM To 11:59PM

那么如何验证开始时间小于结束时间或结束时间大于开始时间

Start-time < End-time  OR  End-time > St-time

考虑js代码中的时间格式,由于时间格式无法实现差异逻辑

Format: '9:00 AM'
Format: '5:00 PM'
4

5 回答 5

25

Here i got after investigate this.
The best practice if Time Format in 12 Hour-Time Or 24 Hour-Time.

//start time
var start_time = $("#start_time").val();

//end time
var end_time = $("#end_time").val();

//convert both time into timestamp
var stt = new Date("November 13, 2013 " + start_time);
stt = stt.getTime();

var endt = new Date("November 13, 2013 " + end_time);
endt = endt.getTime();

//by this you can see time stamp value in console via firebug
console.log("Time1: "+ stt + " Time2: " + endt);

if(stt > endt) {
    $("#start_time").after('<span class="error"><br>Start-time must be smaller then End-time.</span>');
    $("#end_time").after('<span class="error"><br>End-time must be bigger then Start-time.</span>');
        return false;
}
于 2013-01-15T13:31:32.487 回答
4

您必须将字符串转换为可以根据时间进行比较的值。Date.parse派上用场,虽然你也需要传递一个日期。由于您只关心时间,因此请为两者使用相同的假日期。

if(Date.parse("1-1-2000 " + st) > Date.parse("1-1-2000 " + et)) {
于 2012-06-28T12:49:27.977 回答
3

You can even try the following jquery rule : jQuery.validator.addMethod

   jQuery.validator.addMethod("timeValidator",
   function (value, element, params) {
   var val = new Date('1/1/1991' + ' ' + value);       
   var par = new Date('1/1/1991' + ' ' + $(params).val());
   if (!/Invalid|NaN/.test(new Date(val))) {
           return new Date(val) > new Date(par);
       }

       return isNaN(val) && isNaN(par)
           || (Number(val) > Number(par));
}, 'End Time must be greater than Start Time.');

You can call the rule :

$("#txtToTime").rules('add', { timeValidator: "#txtFromTime" });
于 2015-01-23T08:35:46.977 回答
1

如果它们是select元素并且select元素中的顺序相同,则比较selectedIndex。无需解析日期。

于 2012-06-28T13:10:23.143 回答
0

将它们转换为 Date 对象:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

然后使用通常的比较器:

用 JavaScript 比较两个日期

于 2012-06-28T12:51:57.333 回答