-1

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"

Ilya
  • 135
  • 1
  • 2
  • 10
  • This might help: https://stackoverflow.com/questions/6403851/parsing-time-strings-like-1h-30min – user May 15 '20 at 18:07
  • Does this answer your question? [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion) – Ali Ahmad May 15 '20 at 18:18
  • @AliAhmad, it is useful, but I need to get result in the same format, like this "01:04:415", and I still don't understand how to do it – Ilya May 15 '20 at 19:07
  • No, don't use `Date` because that class is poory designed and long outdated. Use java.time, the modern Java date and time API. – Ole V.V. May 15 '20 at 19:20
  • 1
    Do your strings represent points in time, so approximately 3 and 4 minutes past the hour, or do they represent amounts of time (e.g., durations) that you need to subtract? The correct approach is different for the two cases. – Ole V.V. May 15 '20 at 19:22
  • @OleV.V. If I understood correctly, 1 case. This is about racing. Racer starts lap in startTime and finishes in finishTime. I need to calculate how long it takes hime and get the result in the same format – Ilya May 15 '20 at 19:29
  • 1
    In that case I’d consider the answers by Arvind Kumar Avinash and akuzminykh correct. Isn’t it a bit confusing to have the duration of the lap in the same format as the points in time? – Ole V.V. May 15 '20 at 19:48

2 Answers2

1

Here is an example of how to do that using java.time:

// create dtf for pattern where mm is minutes, ss is seconds, SSS is millis
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("mm:ss.SSS");

// we need to add a default value for hour so the parsing with LocalTime works
formatter = new DateTimeFormatterBuilder()
        .append(formatter)
        .parseDefaulting(ChronoField.HOUR_OF_DAY, 1)
        .toFormatter();

// parse the values
LocalTime t1 = LocalTime.parse("02:58.917", formatter);
LocalTime t2 = LocalTime.parse("04:03.332", formatter);

// get the millis between t1 and t2
System.out.println(t1.until(t2, ChronoUnit.MILLIS));

// another way
System.out.println(ChronoUnit.MILLIS.between(t1, t2));

// you can get the result in the same format by adding the difference
// to a new LocalTime with all set to zero and using the formatter
LocalTime delta = LocalTime.of(1, 0, 0, 0)
        .plus(t1.until(t2, ChronoUnit.MILLIS), ChronoUnit.MILLIS);
System.out.println(delta.format(formatter));
akuzminykh
  • 4,522
  • 4
  • 15
  • 36
  • But what I can do, if I need to get result in the same format, like this "01:04:415"? – Ilya May 15 '20 at 19:06
  • @Ilya You can do that by creating a new `LocalTime` with all set to zero and adding the difference in millis to it. Then using the formatter gives you the desired `String`. Check out the edit and feel free to accept the answer. – akuzminykh May 15 '20 at 19:22
  • Most of the answer is good. Using yet one more `LocalTime` for the duration between the first two is incorrect. Use a `Duration` as in the answer by Arvind Kumar Avinash. It’s also simpler. – Ole V.V. May 15 '20 at 19:45
  • @OleV.V. Thanks for the consideration. I'll keep it as it is because it's an alternative. It's not incorrect, the result is the same. `Duration` may seem a bit more convenient though. – akuzminykh May 15 '20 at 20:05
  • Can I ask one more question? I was wondering how it works with hours, and tried this code DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss.SSS"); LocalTime t1 = LocalTime.parse("01:02:58.917", formatter); But it failed. Can you tell what the problem? – Ilya May 15 '20 at 20:43
  • @Ilya You have to open a seperate question for that. – akuzminykh May 16 '20 at 09:27
1

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
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110