Java 减去 LocalTime

2022-08-31 22:22:40

我有两个对象:LocalTime

LocalTime l1 = LocalTime.parse("02:53:40");
LocalTime l2 = LocalTime.parse("02:54:27");

我怎么能在几分钟内发现它们之间的差异?


答案 1

使用 或 ,如 api 所述untilbetween

import java.time.LocalTime;
import static java.time.temporal.ChronoUnit.MINUTES;

public class SO {
    public static void main(String[] args) {
        LocalTime l1 = LocalTime.parse("02:53:40");
        LocalTime l2 = LocalTime.parse("02:54:27");
        System.out.println(l1.until(l2, MINUTES));
        System.out.println(MINUTES.between(l1, l2));
    }
}

0
0


答案 2

从Java 8开始,您可以使用持续时间类。我认为这给出了最优雅的解决方案:

long elapsedMinutes = Duration.between(l1, l2).toMinutes();

推荐