9

I am trying to compare to strings:

Start Time: 10:00 End Time: 12:00

In actuality there is a start time array that contains my values and an end time array. In this case, it would be structured as such:

 StartTimes[0] = "10:00"
 EndTimes[0] = "12:00"

What is the best way (using java) to find out the duration between the times. The start time will always be before the end time. Should I try to separate the string by minute and hour using regex, then parse the hour and parse the minute, compare, then using that info determine the difference, or is their a method to compare times in java? Note these times are in a 24 hour format, so for an ex. 1:00 PM would display as 13:00.

Baby
  • 5,062
  • 3
  • 30
  • 52
user3505931
  • 259
  • 2
  • 4
  • 10

6 Answers6

20

You can find the duration using

    String startTime = "10:00";
    String endTime = "12:00";
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    Date d1 = sdf.parse(startTime);
    Date d2 = sdf.parse(endTime);
    long elapsed = d2.getTime() - d1.getTime(); 
    System.out.println(elapsed);
sps
  • 315
  • 1
  • 3
  • The troublesome old date-time classes used here are now legacy, supplanted by the modern *java.time* classes built into Java 8 and later. – Basil Bourque Jan 08 '18 at 16:48
  • 1
    must `import java.text.SimpleDateFormat;` & surround with try-catch block. – Benny Nov 29 '20 at 11:57
6

java.time In Java 8

I don't have a computer handy to try this, but you might be able to do something like this in the new java.time package in Java 8. Do not confuse the new java.time with the notoriously troublesome old java.util.Date and .Calendar classes bundled with Java.

LocalTime start = LocalTime.parse( "11:00" );
LocalTime stop = LocalTime.parse( "14:00" );
Duration duration = Duration.between( start, stop );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • and how to know that the time is passed by 20 minutes or before 20 minutes? @Basil... – gumuruh Jul 23 '22 at 02:06
  • @gumuruh Do you mean how to tell if the second time comes before or after the first? Duration is positive if first comes before second, otherwise negative. See [`Duration#isNegative`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/Duration.html#isNegative()). – Basil Bourque Jul 23 '22 at 02:13
  • 1
    @gumuruh Or do you mean “How to tell if duration exceeds 20 minutes in total length?” In that case: `if ( duration.toMinutes() > 20 ) { … }` – Basil Bourque Jul 23 '22 at 02:17
  • alright.... you're correct...! It's matched what we've got so far.... – gumuruh Jul 23 '22 at 02:26
1

Use split method to split the 2 times and calculate and parse the duration from there:

sample from your question:

String StartTimes = "10:00";
String EndTimes = "12:00";
String startTimeParse[] = StartTimes.split(":");
String endTimeParse[] = EndTimes.split(":");
int firstHour = Integer.parseInt(startTimeParse[0]);
int firstMinute = Integer.parseInt(startTimeParse[1]);
int secondHour = Integer.parseInt(endTimeParse[0]);
int secondMinute = Integer.parseInt(endTimeParse[1]);
int durattionHour = secondHour - firstHour;
int durattionMinutes = secondMinute - firstMinute;
System.out.println("Duration : " +durattionHour+":"+durattionMinutes );
user3505931
  • 259
  • 2
  • 4
  • 10
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
1

there is no such method to compare.

you can split the time string using ':'. then parse hour and minute into integer. then calculate the duration.

int parseTimeString(String s) {
    String[] t = s.split(":");
    return Integer.parseInt(t[0]) * 60 + Integer.parseInt(t[1]); // minutes since 00:00
}

int durationInMinute = parseTimeString(EndTimes[0]) - parseTimeString(StartTimes[0]);
Xing Fei
  • 287
  • 1
  • 6
0

You should create a Date(now) and add Hour, Minute in it. Get long time and calculate duration.

    Date now = new Date();
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timezone));
    Calendar.setTime(now);
    calendar.add(Calendar.Hour, 12);
    calendar.add(Calendar.MINUTE, 00);
    Date start = calendar.getTime();

    calendar.add(Calendar.Hour, 10);
    calendar.add(Calendar.MINUTE, 00);
    Date end = calendar.getTime();

    try {
        // in milliseconds
        long diff = d2.getTime() - d1.getTime();

        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;

        System.out.print(diffHours + " hours, ");
        System.out.print(diffMinutes + " minutes, ");

    } catch (Exception e) {
        e.printStackTrace();
    }
Phong Ca
  • 17
  • 2
0

You can use java.text.SimpleDateFormat and java.util.concurrent.TimeUnit to help you parse, compare, format to the desired format.

SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = format.parse(StartTimes[i]);
Date date2 = format.parse(EndTimes[i]);
long millis = date2.getTime() - date1.getTime(); 

String hourminute = String.format("%02d:%02d",   TimeUnit.MILLISECONDS.toHours(millis),
                                                TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)));
                    System.out.println(hourminute);

The complete code could be something like this:

import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import java.util.Date;

class TimeCompare
{
    public static void main (String[] args) throws java.lang.Exception
    {

        String[] StartTimes = {"10:00", "7:00"};
        String[] EndTimes = {"12:00", "14:56"};
        for (int i=0; i<StartTimes.length; i++){
            if (StartTimes!=null && StartTimes.length>0 && EndTimes!=null &&EndTimes.length>0){
                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                Date date1 = format.parse(StartTimes[i]);
                Date date2 = format.parse(EndTimes[i]);
                long millis = date2.getTime() - date1.getTime(); 

                String hourminute = String.format("%02d:%02d",   TimeUnit.MILLISECONDS.toHours(millis),
                                            TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)));
                System.out.println(hourminute);

            }
        }

    }


}

sources:

How to calculate time difference in java?

How to convert milliseconds to "hh:mm:ss" format?

Community
  • 1
  • 1