Click here to Skip to main content
15,904,655 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have two timings with hh:mm:ss format in string.How to compare two strings.

What I have tried:


Time comparation in java these are in string?
Updated 13-Feb-17 10:13am
[no name] 13-Feb-17 12:37pm    
You don't. You compare date times, not strings.

Try this and adapt:
import java.util.*;
import java.lang.*;
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;

class Rextester
    public static void main(String args[])
        String startTime = "10:15:20 am";
        String endTime = "12:30:37 pm";

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
        try {
            Date d1 = sdf.parse(startTime);
            Date d2 = sdf.parse(endTime);
            long elapsed = d2.getTime() - d1.getTime(); 
            int hours = (int) Math.floor(elapsed / 3600000);
            int minutes = (int) Math.floor((elapsed - hours * 3600000) / 60000);
            int seconds = (int) Math.floor((elapsed - hours * 3600000 - minutes * 60000) / 1000);
            System.out.format("From %s to %s%n", startTime, endTime);
            System.out.format("Time elapsed %d milliseconds%n", elapsed);
            System.out.format("%d hours %d minutes %d seconds%n", hours, minutes, seconds);

         } catch (ParseException e) {
or view Demo[^]
reference: SimpleDateFormat : Date Format « Data Type « Java Tutorial[^]
Share this answer
With all the details you didn't gave us, about any answer is right.

This time format is the 24 hours time format as used in Europa, also known as military time format in USA.
If the goal is to compare like < = >, direct string comparison do the trick.
If the goal is to get the time difference, a conversion to time datatype is necessary.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900