Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare start time amd end time with jquery?

Here the code

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

if i have time range as follows

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

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

then how to validate start-time less then end-time OR end-time greater then start-time

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

consider time format in js-code, due to time-format am unable to implement difference logic

Format: '9:00 AM'
Format: '5:00 PM'
like image 288
Frank Avatar asked Jun 28 '12 12:06

Frank


2 Answers

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;
}
like image 95
Frank Avatar answered Nov 15 '22 06:11

Frank


You have to convert strings to values you can compare in terms of time. Date.parse comes in handy, though you're required to pass a date as well. Since you only care about time, use the same fake date for both.

if(Date.parse("1-1-2000 " + st) > Date.parse("1-1-2000 " + et)) {
like image 29
pimvdb Avatar answered Nov 15 '22 06:11

pimvdb