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

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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");

Solution 2 - Javascript

Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10')
> true

The 1st January is an arbitrary date, doesn't mean anything.

Solution 3 - Javascript

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

Solution 4 - Javascript

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>

Solution 5 - Javascript

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

Solution 6 - Javascript

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");
}

Solution 7 - Javascript

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...

Solution 8 - Javascript

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

Solution 9 - Javascript

> Best way to compare times using convert into ms

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

return minutesOfDay(now) > minutesOfDay(end);

Solution 10 - Javascript

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

Solution 11 - Javascript

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;
}

Solution 12 - Javascript

I think you can put it like this.

var a = "10:20:45";
var b = "5:10:10";

var timeA = new Date();
timeA.setHours(a.split(":")[0],a.split(":")[1],a.split(":")[2]);
timeB = new Date();
timeB.setHours(b.split(":")[0],b.split(":")[1],b.split(":")[2]);

var x= "B is later than A";
if(timeA>timeB) x = "A is later than B";
document.getElementById("demo").innerHTML = x;

<p id="demo"></p>

Solution 13 - Javascript

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

Solution 14 - Javascript

time format should be in HH:mm:ss HH for 24 hour format

if (start_time > end_time)
    console.log('start time is greater than end time')
else console.log('end time is greater than start time')

Solution 15 - Javascript

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;
        }
    }
}

Solution 16 - Javascript

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...
                }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNull PointerView Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow
Solution 2 - JavascriptEvgeny ShadchnevView Answer on Stackoverflow
Solution 3 - JavascripthienView Answer on Stackoverflow
Solution 4 - JavascriptSuresh KrishnamoorthiView Answer on Stackoverflow
Solution 5 - JavascriptKishan PatelView Answer on Stackoverflow
Solution 6 - JavascriptniksvpView Answer on Stackoverflow
Solution 7 - JavascriptpmirandaView Answer on Stackoverflow
Solution 8 - JavascriptGhasem AladaghlouView Answer on Stackoverflow
Solution 9 - JavascriptSublime Laravel DevView Answer on Stackoverflow
Solution 10 - JavascriptpatapizzaView Answer on Stackoverflow
Solution 11 - JavascriptNicolas GiszpencView Answer on Stackoverflow
Solution 12 - JavascriptGameBoy View Answer on Stackoverflow
Solution 13 - JavascriptIrshad KhanView Answer on Stackoverflow
Solution 14 - JavascriptLakmal HarshanaView Answer on Stackoverflow
Solution 15 - JavascriptKamil P.View Answer on Stackoverflow
Solution 16 - JavascriptRichardson V JohnsonView Answer on Stackoverflow