2015-02-05 36 views
13

我有兩個LocalTime對象:的Java減去本地時間

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

我如何在它們之間找到分鐘不同?

回答

15

使用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

你可以這樣做:

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

我不認爲我們應該用新的日期/時間API以毫秒計算 – keuleJ 2015-02-06 06:30:52

5

我這樣做與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 
13

由於Java 8,你可以使用Duration類描述。我認爲這給出了最優雅的解決方案:

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