[javascript] How can I compare two time strings in the format HH:MM:SS?

I have two time strings in HH:MM:SS format. For example, str1 contains 10:20:45, str2 contains 5:10:10.

How can I compare the above values?

This question is related to javascript

The answer is


Convert to seconds those strings:

var str1 = '10:20:45';
var str2 = '5:10:10';

str1 =  str1.split(':');
str2 =  str2.split(':');

totalSeconds1 = parseInt(str1[0] * 3600 + str1[1] * 60 + str1[0]);
totalSeconds2 = parseInt(str2[0] * 3600 + str2[1] * 60 + str2[0]);

// compare them

if (totalSeconds1 > totalSeconds2 ) { // etc...

Try this code for the 24 hrs format of time.

<script type="text/javascript">
var a="12:23:35";
var b="15:32:12";
var aa1=a.split(":");
var aa2=b.split(":");

var d1=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa1[0],10),parseInt(aa1[1],10),parseInt(aa1[2],10));
var d2=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa2[0],10),parseInt(aa2[1],10),parseInt(aa2[2],10));
var dd1=d1.valueOf();
var dd2=d2.valueOf();

if(dd1<dd2)
{alert("b is greater");}
else alert("a is greater");
}
</script>

I'm not so comfortable with regular expressions, and my example results from a datetimepicker field formatted m/d/Y h:mA. In this legal example, you have to arrive before the actual deposition hearing. I use replace function to clean up the dates so that I can process them as Date objects and compare them.

function compareDateTimes() {
    //date format ex "04/20/2017 01:30PM"
    //the problem is that this format results in Invalid Date
    //var d0 = new Date("04/20/2017 01:30PM"); => Invalid Date

    var start_date = $(".letter #depo_arrival_time").val();
    var end_date = $(".letter #depo_dateandtime").val();

    if (start_date=="" || end_date=="") {
        return;
    }
    //break it up for processing
    var d1 = stringToDate(start_date);
    var d2 = stringToDate(end_date);

    var diff = d2.getTime() - d1.getTime();
    if (diff < 0) {
        end_date = moment(d2).format("MM/DD/YYYY hh:mA");
        $(".letter #depo_arrival_time").val(end_date);
    }
}

function stringToDate(the_date) {
    var arrDate = the_date.split(" ");
    var the_date = arrDate[0];
    var the_time = arrDate[1];
    var arrTime = the_time.split(":");
    var blnPM = (arrTime[1].indexOf("PM") > -1);
    //first fix the hour
    if (blnPM) {
        if (arrTime[0].indexOf("0")==0) {
            var clean_hour = arrTime[0].substr(1,1);
            arrTime[0] = Number(clean_hour) + 12;
        }
        arrTime[1] = arrTime[1].replace("PM", ":00");
    } else {
        arrTime[1] = arrTime[1].replace("AM", ":00");
    }
    var date_object =  new Date(the_date);
    //now replace the time
    date_object = String(date_object).replace("00:00:00", arrTime.join(":"));
    date_object =  new Date(date_object);

    return date_object;
}

As Felix Kling said in the comments, provided your times are based on a 24 hour clock (and they should be if there's no AM/PM) and provided they are always in the format HH:MM:SS you can do a direct string comparison:

var str1 = "10:20:45",
    str2 = "05:10:10";

if (str1 > str2)
    alert("Time 1 is later than time 2");
else
    alert("Time 2 is later than time 1");

Try this code.

var startTime = "05:01:20";
var endTime = "09:00:00";
var regExp = /(\d{1,2})\:(\d{1,2})\:(\d{1,2})/;
if(parseInt(endTime .replace(regExp, "$1$2$3")) > parseInt(startTime .replace(regExp, "$1$2$3"))){
alert("End time is greater");
}

I think you can put it like this.

_x000D_
_x000D_
var a = "10:20:45";_x000D_
var b = "5:10:10";_x000D_
_x000D_
var timeA = new Date();_x000D_
timeA.setHours(a.split(":")[0],a.split(":")[1],a.split(":")[2]);_x000D_
timeB = new Date();_x000D_
timeB.setHours(b.split(":")[0],b.split(":")[1],b.split(":")[2]);_x000D_
_x000D_
var x= "B is later than A";_x000D_
if(timeA>timeB) x = "A is later than B";_x000D_
document.getElementById("demo").innerHTML = x;
_x000D_
<p id="demo"></p>
_x000D_
_x000D_
_x000D_


Date object in js support comparison, set them same date for compare hh:mm:ss :

new Date ('1/1/1999 ' + '10:20:45') > new Date ('1/1/1999 ' + '5:10:10') 
> true

I improved this function from @kamil-p solution. I ignored seconds compare . You can add seconds logic to this function by attention your using.

Work only for "HH:mm" time format.

function compareTime(str1, str2){
    if(str1 === str2){
        return 0;
    }
    var time1 = str1.split(':');
    var time2 = str2.split(':');
    if(eval(time1[0]) > eval(time2[0])){
        return 1;
    } else if(eval(time1[0]) == eval(time2[0]) && eval(time1[1]) > eval(time2[1])) {
        return 1;
    } else {
        return -1;
    }
}

example

alert(compareTime('8:30','11:20'));

Thanks to @kamil-p


Best way to compare times using convert into ms

var minutesOfDay = function(m){
      return m.minutes() + m.hours() * 60;
    }

return minutesOfDay(now) > minutesOfDay(end);

var startTime = getTime(document.getElementById('startTime').value);
                var endTime = getTime(document.getElementById('endTime').value);


                var sts = startTime.split(":");
                var ets = endTime.split(":");

                var stMin = (parseInt(sts[0]) * 60 + parseInt(sts[1]));
                var etMin = (parseInt(ets[0]) * 60 + parseInt(ets[1]));
                if( etMin > stMin) {
                // do your stuff...
                }

var str1 = "150:05:05",
var str2 = "80:04:59";   

function compareTime(str1, str2){

    if(str1 === str2){
        return 0;
    }

    var time1 = str1.split(':');
    var time2 = str2.split(':');

    for (var i = 0; i < time1.length; i++) {
        if(time1[i] > time2[i]){
            return 1;
        } else if(time1[i] < time2[i]) {
            return -1;
        }
    }
}

Set the extracted part of the time to variables.

// If you don't have the second part then set it to 00.

 //Create date object and set the time to that
 var startTimeObject = new Date();
 startTimeObject.setHours(startHour, startMinute, startSecond);

 //Create date object and set the time to that
 var endTimeObject = new Date(startTimeObject);
 endTimeObject.setHours(endHour, endMinute, endSecond);

 //Now we are ready to compare both the dates
 if(startTimeObject > endTimeObject) {
     alert('End time should be after start time.');
 }
 else {
     alert('Entries are perfect.');
 }

You can easily do it with below code:

Note: The second argument in RegExp is 'g' which is the global search flag. The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern. Below code only works if the time is in HH:MM:SS format i.e. 24 hour time format.

var regex = new RegExp(':', 'g'),
    timeStr1 = '5:50:55',
    timeStr2 = '6:17:05';
if(parseInt(timeStr1.replace(regex, ''), 10) < parseInt(timeStr2.replace(regex, ''), 10)){
  console.log('timeStr1 is smaller then timeStr2');
} else {
  console.log('timeStr2 is smaller then timeStr1');
}

You could compare the two values right after splitting them with ':'.