将2个带毫秒的字符串转换成日期并计算时差java

Converting 2 strings with milliseconds into date and calculating time difference java

我有 2 个带有分、秒和毫秒的字符串

String startTime = "02:58.917"
String finishTime = "04:03.332"

我需要计算时差。据我所知(但我不确定)最简单的方法是将它们转换为 Date 类型,但我不知道如何正确地做,尤其是毫秒。 P.S。如果有人知道我如何在不转换为日期的情况下计算时差,它也适用。 请帮忙!

UPD:我需要获得相同格式的结果,例如“01:04:415”

这是一个如何使用 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));

您可以通过计算开始时间和结束时间之间的差来获得java.time.Duration对象。然后,您可以从 Duration 对象中获取分钟部分、秒部分和毫秒部分,以获得所需的输出。

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);
    }
}

输出:

The difference is 01:04:415