I have two strings which are used to store time in the format hh:mm.I want to the compare these two to know which time is greater.Which is the easiest way to go about this?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, if they’re actually hh:mm (including leading zeroes, and in 24-hour format) then you can just compare them lexicographically (i.e. using
String.compareTo(String)). That’s the benefit of a sortable format 🙂Of course, that won’t check that both values are valid times. If you need to do that, you should probably parse both times: check the length, check the colon, parse two substrings, and probably multiply the number of hours by 60 and add it to the number of minutes to get a total number of minutes. Then you can compare those two totals.
EDIT: As mentioned in the comments, if you do need to parse the values for whatever reason, personally I would recommend using Joda Time (possibly a cut down version, given the mobile nature) rather than
SimpleDateTimeFormatandDate. Joda Time is a much nicer date and time API than the built-in one.