Java 减去本地时间

Java subtract LocalTime

我有两个 LocalTime 对象:

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

如何在分钟内找到它们之间的差异?

你可以这样做:

long dif = Math.abs (l1.getLocalMillis () - l2.getLocalMillis ());
TimeUnit.MINUTES.convert (dif, TimeUnit.MILLISECONDS);

我用 ChronoUnit

long minutesBetween = ChronoUnit.MINUTES.between(l1,l2);

例子

    LocalTime localTime=LocalTime.now();
    LocalTime localTimeAfter5Minutes=LocalTime.now().plusMinutes(5);
    Long minutesBetween=ChronoUnit.MINUTES.between(localTime,localTimeAfter5Minutes);
    System.out.println("Diffrence between time in munutes : "+minutesBetween);

输出

Diffrence between time in munutes : 5

使用untilbetween,如api

所述
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

因为 Java 8 你可以使用 Duration class。我认为这给出了最优雅的解决方案:

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