Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two Time in Strings

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.

like image 263
user3505931 Avatar asked Apr 25 '14 02:04

user3505931


People also ask

How do you compare two times in a string in python?

Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.

Can we use == operator to compare two strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do I compare two characters in a string?

strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0. For example, i will be 0 in the following code: char str1[] = "Look Here"; char str2[] = "Look Here"; int i = strcmp(str1, str2);


1 Answers

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);
like image 137
sps Avatar answered Oct 11 '22 17:10

sps