I have 2 strings with minutes, seconds and miliseconds
String startTime = "02:58.917"
String finishTime = "04:03.332"
and I need to calculate time difference. As i understand (but I'm not sure) the most simple way is to convert them into Date type, but I don't know how to do it correctly, escpecially with milliseconds. P.S. If anybode know how I can calculate time difference without converting to Date, it also fits. Help pls!
UPD: I need to get result in the same format, like this "01:04:415"
You can obtain java.time.Duration
object by calculating the difference between the start time and finish time. Then, you can get the minute part, second part and millisecond part from the Duration
object to get the required output.
import java.text.ParseException;
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
public class Main {
public static void main(String[] args) throws ParseException {
String startTime = "02:58.917";
String finishTime = "04:03.332";
// Create a format by defaulting the hour to any value e.g. 0
DateTimeFormatter format = new DateTimeFormatterBuilder().append(DateTimeFormatter.ofPattern("mm:ss.SSS"))
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0).toFormatter();
LocalTime firstTime = LocalTime.parse(startTime, format);
LocalTime secondTime = LocalTime.parse(finishTime, format);
Duration diff = Duration.between(firstTime, secondTime);
String msms = String.format("%02d:%02d:%03d", diff.toMinutesPart(), diff.toSecondsPart(), diff.toMillisPart());
System.out.println("The difference is " + msms);
}
}
Output:
The difference is 01:04:415