Midhun Midhun - 7 days ago 6
Javascript Question

jQuery-validating start time and end time selected using time picker

I want to validate start time and end time selected using timepicker which is in 12 hr format. The end time should be greater than the start time. I used an

if
statement but when the test is using values such as 8:00 AM as start time and 1:00 PM as end time, it is not working. What can I do to solve this problem. Someone please help me with this. I am stuck with this since yesterday. I want just time ,i don't need date.

$("#dateTimeAddButton").click(function ()
{
var Date=$('#myDatePickerId').val()
var startTime = $('#i').val();
var endTime = $('#i1').val();
if (startTime > endTime)
{
alert('End time always greater then start time.');
}
});

Answer

First convert to lowest denominational (minute here). Then compare it.

st = minFromMidnight(startTime);
et = minFromMidnight(endTime);
if(st>et){
    alert("End time must be greater than start time");
}

function minFromMidnight(tm){
 var ampm= tm.substr(-2)
 var clk = tm.substr(0, 5);
 var m  = parseInt(clk.match(/\d+$/)[0], 10);
 var h  = parseInt(clk.match(/^\d+/)[0], 10);
 h += (ampm.match(/pm/i))? 12: 0;
 return h*60+m;
}