Categories
JavaScript Answers

How to compare two time strings in the format HH:MM:SS with JavaScript?

Spread the love

Sometimes, we want to compare two time strings in the format HH:MM:SS with JavaScript.

In this article, we’ll look at how to compare two time strings in the format HH:MM:SS with JavaScript.

How to compare two time strings in the format HH:MM:SS with JavaScript?

To compare two time strings in the format HH:MM:SS with JavaScript, we can compare the time strings directly if the strings are in 24 hour format and there’s no am or pm in them.

For instance, we write

const str1 = "10:20:45";
const str2 = "05:10:10";

if (str1 > str2) {
  console.log("Time 1 is later than time 2");
} else {
  console.log("Time 2 is later than time 1");
}

to compare str1 and str2 directly.

The strings are in 24 hour format and there’s no am or pm in them, so we can do the comparison directly.

Conclusion

To compare two time strings in the format HH:MM:SS with JavaScript, we can compare the time strings directly if the strings are in 24 hour format and there’s no am or pm in them.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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