2015-08-24 53 views
-3

我有一段24小時的格式,像這樣23:08 現在我想從這個例子的格式中獲得剩餘的小時和分鐘,比如3h 10m,我怎麼能得到這個?任何想法?我有其他線程的解決方案,但他們都計算日期也,但我不想要日期,它將始終從今天計算,如果時間從今天過去,那麼它會給第二天的剩餘時間。如何從現在到一個特定的24小時格式化時間在Android的剩餘小時?

+0

這是不清楚。請詳細說明。爲什麼結果應該是3h 10m? –

+0

我剛剛舉了一個例子,它會顯示確切的剩餘時間格式,沒有其他 – Reyjohn

+1

可能重複的[計算日期/時間差異在java](http://stackoverflow.com/questions/5351483/calculate-date- time-difference-in-java) –

回答

0

對不起,我誤解了這個問題。這是新的答案。

public static void main(String[] args) { 
    Calendar cal = Calendar.getInstance(); 
    int nowHour = cal.get(Calendar.HOUR_OF_DAY); 
    int nowMin = cal.get(Calendar.MINUTE); 
    System.out.printf("Now is: %02d:%02d%n", nowHour, nowMin); 
    test(nowHour, nowMin, "00:00"); 
    test(nowHour, nowMin, "01:00"); 
    test(nowHour, nowMin, "11:59"); 
    test(nowHour, nowMin, "12:00"); 
    test(nowHour, nowMin, "23:08"); 
    test(nowHour, nowMin, "23:59"); 
} 
private static void test(int nowHour, int nowMin, String endTime) { 
    Matcher m = Pattern.compile("(\\d{2}):(\\d{2})").matcher(endTime); 
    if (! m.matches()) 
     throw new IllegalArgumentException("Invalid time format: " + endTime); 
    int endHour = Integer.parseInt(m.group(1)); 
    int endMin = Integer.parseInt(m.group(2)); 
    if (endHour >= 24 || endMin >= 60) 
     throw new IllegalArgumentException("Invalid time format: " + endTime); 
    int minutesLeft = endHour * 60 + endMin - (nowHour * 60 + nowMin); 
    if (minutesLeft < 0) 
     minutesLeft += 24 * 60; // Time passed, so time until 'end' tomorrow 
    int hours = minutesLeft/60; 
    int minutes = minutesLeft - hours * 60; 
    System.out.println(hours + "h " + minutes + "m until " + endTime); 
} 

輸出:

Now is: 02:15 
21h 45m until 00:00 
22h 45m until 01:00 
9h 44m until 11:59 
9h 45m until 12:00 
20h 53m until 23:08 
21h 44m until 23:59 
+0

你的答案做了一些工作,但它不準確只是顯示一些隨機值,你可以檢查是否有什麼問題嗎? – Reyjohn

+0

我已經得到了你的答案,但它現在計算的是00:00 AM,你能從現在的確切時間計算出來嗎? – Reyjohn

1

這會給你的當前時間

 Calendar cal = Calendar.getInstance(); 
     Date d1 = cal.getTime();// current time 

這將計算分鐘和小時的差異

 Date d2;//your time 
     long diff = d2.getTime() - d1.getTime(); 
     long diffHours = diff/(60 * 60 * 1000); 
     long diffMinutes = diff/(60 * 1000) % 60; 
相關問題