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.
Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods 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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With