2011-09-21 32 views
3

我想獲得一個時間戳的時間,但我不斷得到錯誤的時間,當我使用Calendar.HOURCalendar.MINUTE,不管它是什麼時間戳它告訴我小時是10和分鐘是12.日曆給我錯誤的小時和分鐘

現在當我使用Calendar.getTime()它給了我正確的時間,所以我不明白?我只是想在12小時格式的小時和分鐘

這是我如何去這樣做

public static String getRealTime(long time){ 

      Calendar cal = Calendar.getInstance(); 
    Log.d("Calendar",String.valueOf(time)); 
    cal.setTimeInMillis(time); 
    Date timeS = cal.getTime(); 
    String sTime = timeS.toString(); // gives correct time in 24hr format 
    int hr = cal.HOUR;    // gives me 10 no matter what the timestamp is 
    int min = cal.MINUTE;   // gives me 12 no matter what the timestamp is 
    String dMin = getDoubleDigit(min); 
    int ampm = cal.AM_PM; 
    String m = new String(); 
    if(ampm == 0){ 
     m = "AM"; 
    }else{ 
     m="PM"; 
    } 
    String rtime = String.valueOf(hr)+":"+dMin+" "+m; 
    return rtime; 
} 

這麼說時間戳1316626200000 cal.getTime()給了我Wed Sep 21 13:30:00 EDT 2011這將是正確的時間,但cal.HOUR給我10小時,這顯然不是它應該是。爲什麼這樣做?

回答

13

cal.HOURcal.MINUTE是用於Calendar方法調用的靜態最終整數。你可以使用此代碼來得到正確的結果:

int hr = cal.get(Calendar.HOUR); 
    int min = cal.get(Calendar.MINUTE); 

請注意,我從CalendarHOURMINUTE領域,而不是你的對象cal。從實例化對象調用靜態成員是不好的做法。

+0

上得到了現在的感謝 – tyczj

+0

大幫了我很多:) –

2

偉大而全能的Android參考頁面來拯救! :D http://developer.android.com/reference/java/util/Calendar.html

所以,這裏是爲什麼一些這些東西沒有返回你期待的結果的內幕。首先,Calendar.HOUR不是對當前小時的引用。首先提示的是它是全部大寫的,Java慣例意味着這是一個常量(又名final)字段。如果你在Eclipse中開發它可能會提出一個警告,說你應該引用類名爲Calendar的靜態變量,而不是使用實例cal。第二個提示:參考頁是這麼說的! ;)

那麼,你應該怎麼用Calendar.HOUR呢?這是一個靜態常量,因此您可以使用cal.get()來查明。 (見參考頁http://developer.android.com/reference/java/util/Calendar.html#get(int)

但是!有一個更簡單的方法。你可能會尋找的代碼可能是這樣的:

public static String getRealTime(long time){ 
    return new SimpleDateFormat("HH:mm").format(new Date(time)); 
    //if you'd rather have the current time, just use new Date() without the time as a parameter 
} 

另一位用戶問一個八九不離十類似的東西,也有一些其他實現此頁Display the current time and date in an Android application

+0

Poo,我花了很長時間來寫我的答案! :d – Bob