2011-09-09 196 views
2

我試圖使用JODA簡單地將一個數字時間戳(表示Unix紀元時間的long)轉換爲一個Month Day, Year字符串。JODA瘋狂?

這裏的代碼,我只是跑了幾秒鐘前:

long lTimestamp = 1315600867; // Current timestamp is approx 9/9/11 3:41 PM EST 

    DateTime oTimestamp = new DateTime(lTimestamp); 
    String strMon, strDay, strYear; 
    strMon = oTimestamp.monthOfYear().getAsText(Locale.ENGLISH); 
    strDay = oTimestamp.dayOfMonth().getAsText(Locale.ENGLISH); 
    strYear = oTimestamp.year().getAsText(Locale.ENGLISH); 

    String strDate = strMon + " " + strDay + ", " + strYear; 

    System.out.println("Converted timestamp is : " + strDate); 

輸出到這是1970年1月16日

難道這使得任何任何人?!?!

+0

我在http://www.epochconverter.com/上做了一個快速檢查。您的輸入很長是正確的。 – Freiheit

+1

'DateTime'的'long'參數應該以毫秒爲單位,而不是秒。 – lhballoti

+0

@Freiheit:epochconverter假設*秒*自紀元,而不是毫秒。 –

回答

8

long傳遞到DateTime constructor,就是要在毫秒,不 - 所以使用1315600867000L來代替,而這一切都很好。

文檔狀態:

構建一個實例從1970-01-01T00設置到毫秒:00:00Z在默認時區使用ISOChronology。

如果你得到一個值,這已經是在幾秒鐘內,你只需要1000繁殖:

long timestampInSeconds = getValueFromDatabase(); 
long timestampInMillis = timestampInSeconds * 1000L; 
DateTime dt = new DateTime(timestampInMillis); 

其實我建議你使用在這種情況下,而不是DateTimeInstant - 你真的沒有時間區考慮。如果您要使用DateTime,則應明確指定時區,例如,

DateTime dt = new DateTime(timestampInMillis, DateTimeZone.UTC); 
+0

感謝@Jon - 但是我的變量lTimestamp實際上不是硬編碼的,它從內嵌數據庫(SQLite)中拉回數字。實際的調用如下所示:lTimestamp = getCreationTimestamp()。我只是嘗試將它轉換爲一個字符串,在最後連接一個「L」,然後將它解析回一長串,現在從Long內部得到一個NumberFormatException。有沒有優雅的方法來破解這個? – IAmYourFaja

+0

@Mara,試試Long.valueOf(「」+ yourLongValue +「L」); – dantuch

+0

謝謝@dantuch,但仍然無法正常工作。與上述情況相同。我欣賞這個建議。 – IAmYourFaja