nmkkannan nmkkannan - 5 months ago 18
jQuery Question

how to compare two time variables in jquery without date

this is my jquery code.#StartTime and #EndTime is input form tag.starttime and entime contain time values only,not date value.then how to compare this two time values in jquery.
example:starttimeval=8:00 AM endtimeval=9:00 PM (not date value inside the variable only time)

$(function() {
$('#StartTime').datetimepicker({
datepicker : false,
format : 'g:i A'
});
$('#EndTime').datetimepicker({
datepicker : false,
format : 'g:i A'

});
var starttime= $("#StartTime").val();
var endtime= $("#EndTime").val();
});


this is my form image.it's show time values.enter image description here

Answer

Assuming the times are always on the hour, then here is a function that will convert the input value you have to 24 hour:

function getHour24(timeString)
{
    time = null;
    var matches = timeString.match(/^(\d{1,2}):00 (\w{2})/);
    if (matches != null && matches.length == 3)
    {
        time = parseInt(matches[1]);
        if (matches[2] == 'PM')
        {
            time += 12;
        }
    }
    return time;
}

Then if you want to find the difference, just do:

var starttime =  getHour24($("#StartTime").val());
var endtime = getHour24(($("#EndTime").val());

var timeDifference = endtime - starttime;

Hope that helps!

Comments