How To Compare Two Time Strings Formatted As HH:MM:SS In JavaScript

Compare two Time strings formatted as HH:MM:SS in JavaScript

This article will show you how to compare two time strings formatted as HH:MM:SS in Javascript. Let’s find out methods for this task below.

Compare two time strings formatted as HH:MM:SS in Javascript

Use conditional statements

Now we have two time strings formatted as HH:MM:SS to compare these two, we use greater/less than comparison, which value is greater. And to display the results that satisfy the condition, we use the if-else conditional statement. See the example below for a better understanding.

Code sample:

let timeStr1 = '12:18:02';
let timeStr2 = '17:27:36';
 
// Use the if-else statement to compare timeStr1 vs timeStr2
if(timeStr1 > timeStr2){
    console.log('timeStr2 is less than timeStr1')
}else if( timeStr1<timeStr2){
    console.log('timeStr1 is less than timeStr2')
}else document.write('both are equal')

Output

timeStr1 is less than timeStr2

Use conditional operators

The ternary operator is a handy operator in JavaScript that is like a shortened version of the if-else statement.

Syntax

Condition ? value1 : value 2

Simple, if the condition before the ? If it returns true, it will return 1, and false will return 2.

Code sample:

let val = 32;
val == null ? val = 10 : val;
console.log(val);

Output

32

The above example shows that the conditional operator checks the val variable to be null. If true equals null, it will execute the next statement and set the variable’s value to 10. But in fact, the val variable is not null, so it executes the command on the right : and prints the result.

Similarly, we can also use the conditional operator to compare two time strings, but it is a bit more complicated.

Code sample

let timeStr1 = '19:18:02';
let timeStr2 = '20:27:36';
 
// Use conditional operators to compare timeStr1 vs timeStr2
timeStr1 == timeStr2 ? console.log('both are equal') : timeStr1 > timeStr2 ?
console.log('timeStr2 is less than timeStr1') : console.log('timeStr1 is less than timeStr2');

Output

timeStr2 is greater than timeStr1

Summary

Above, I showed you how to compare two time strings formatted as HH:MM:SS in Javascript using the if-else conditional statement and the conditional operator. Logically, both solutions are the same, only the syntax is different, so you can choose any method. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about Javascript in the next lessons here. Have a great day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *