Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 201
Null Pointer Avatar asked Jun 02 '11 08:06

Null Pointer


People also ask

Can we compare dates in string format?

In this very case you can just compare strings date1. compareTo(date2) . EDIT: However, the proper way is to use SimpleDateFormat : DateFormat f = new SimpleDateFormat("yyyy-mm-dd"); Date d1 = f.


Video Answer


2 Answers

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"); 
like image 53
Andy E Avatar answered Oct 04 '22 11:10

Andy E


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.

like image 28
Evgeny Shadchnev Avatar answered Oct 04 '22 11:10

Evgeny Shadchnev