我有兩個LocalTime
對象:的Java減去本地時間
LocalTime l1 = LocalTime.parse("02:53:40");
LocalTime l2 = LocalTime.parse("02:54:27");
我如何在它們之間找到分鐘不同?
我有兩個LocalTime
對象:的Java減去本地時間
LocalTime l1 = LocalTime.parse("02:53:40");
LocalTime l2 = LocalTime.parse("02:54:27");
我如何在它們之間找到分鐘不同?
使用until
或between
,由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));
}
}
你可以這樣做:
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
由於Java 8,你可以使用Duration
類描述。我認爲這給出了最優雅的解決方案:
long elapsedMinutes = Duration.between(l1, l2).toMinutes();
我不認爲我們應該用新的日期/時間API以毫秒計算 – keuleJ 2015-02-06 06:30:52