2015-07-20 52 views
1

我想知道如何查找上次在Java中8:45以來經過了多少時間。自上次「X」時鐘以來經過了多少時間

ex。
時間:8:44 - > 23:59
時間8:46 - > 00.01

我現在有一個比較難看的解決方案。

if (calendar.get(Calendar.HOUR_OF_DAY) >= 8) { 
    if (calendar.get(Calendar.MINUTE) >= 45 || calendar.get(Calendar.HOUR_OF_DAY) > 9) { 
     System.out.println("it between 8:45 and 00:00"); 
    } 
} 
else { 
    System.out.println("its between 00:00 and 8:45"); 
} 
+0

更容易與時期(可在Java 1.8) - [鏈接](https://docs.oracle.com/javase/8/docs/api/java/ time/Period.html) –

+0

我們是24小時直線對話嗎?或者您是否需要考慮由[夏令時](http://stackoverflow.com/tags/dst/info)轉換創建的缺失時間間隔和重複時間重疊? –

回答

0

喜歡的東西:

public void test() { 
    Calendar c = Calendar.getInstance(); 
    Calendar eightFortyFive = Calendar.getInstance(); 
    eightFortyFive.set(Calendar.HOUR, 8); 
    eightFortyFive.set(Calendar.MINUTE, 45); 
    eightFortyFive.set(Calendar.SECOND, 0); 
    eightFortyFive.set(Calendar.MILLISECOND, 0); 
    // You might not need to do this or you may need to use -24. 
    if (eightFortyFive.after(c)) { 
     eightFortyFive.add(Calendar.HOUR, -12); 
    } 
    System.out.println("Time since " + eightFortyFive.getTime() + " = " + new Date(c.getTimeInMillis() - eightFortyFive.getTimeInMillis())); 

} 

從本質上講,你一定要把當前時間,設定時,分,秒和毫秒到你想要的東西,如果需要減去12或24小時。然後,您可以創建一個新的Date,這是兩者之間的區別。

+0

你會想要減去24小時 - 從OP很清楚他正在處理24小時制。 – dcsohl

+0

@dcsohl - 我不確定我真的需要減法。 – OldCurmudgeon

0

如果你只是想獲得日期之間的日子裏,你可以使用類似:

public static void main(String[] args) { 
    long initial = getTime("20-jul-2015 11:09:25"); /*you use System.currentTimeMillis() at the beginning*/ 
    long finalTime = getTime("21-jul-2016 15:21:26"); /*you use System.currentTimeMillis() at the capture of final time.*/ 
    printElapsedTime(initial, finalTime); 
    } 

    private static void printElapsedTime(long initial, long finalTime) { 
    long lapse = finalTime - initial; 
    long secs = (lapse/(1000))%60; 
    long mins = lapse/(1000*60)%60; 
    long hrs = lapse/(1000*60*60)%24; 
    long days = lapse/(1000*60*60*24); 

    StringBuilder lapseMsg = new StringBuilder("Elapsed time since ").append(new Date(initial)).append(" to " + new Date(finalTime)).append(":\r\n"); 
    lapseMsg.append(days).append(" Days, ").append(hrs).append(" Hours, ").append(mins).append(" Minutes, ").append(secs).append(" seconds"); 
    System.out.println(lapseMsg.toString()); 
    } 

    /*just used to get any date to test.*/ 
    private static long getTime(String date) { 
    DateFormat format = DateFormat.getDateTimeInstance(); 
    try { 
     return format.parse(date).getTime(); 
    } catch (ParseException e) { 
     throw new RuntimeException(); 
    } 
    } 

,如果你需要的東西更像是一個你可以使用日曆逝去的幾個月,做一些修正,以複雜的@ OldCurmudgeon解決方案。 (它並不適用於我的方式)

相關問題