2017-04-06 77 views
0

我按照這個API document這個日期格式,這個API需要一個Date頭,他們說,他們只支持GMT日期格式,所以我嘗試了所有吼叫,但沒有一個成功的。我怎樣才能在Java中

@Test 
public void testFormat(){ 
    Date a = new Date("Tue, 08 Dec 2015 06:13:40 GMT"); 
    System.out.println(a); 
    Date b = new Date("Thu, 17 Mar 2012 18:49:58 GMT"); 
    System.out.println(b); 
    System.out.println(b.toGMTString()); // 17 Mar 2012 18:49:58 GMT 
    System.out.println(b.toLocaleString());// 2012-3-18 2:49:58 
    System.out.println(DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT.format(b));//2012-03-18T02:49:58+08:00 
} 

那麼,什麼是這樣Tue, 08 Dec 2015 06:13:40 GMT的格式,我怎樣才能在Java中這種格式?

編輯

輸出

Tue Dec 08 14:13:40 CST 2015 
Sun Mar 18 02:49:58 CST 2012 
17 Mar 2012 18:49:58 GMT 
2012-3-18 2:49:58 
2012-03-18T02:49:58+08:00 

我不只是問的模式,我想知道是否有這種格式的任何標準或名字嗎?

+0

Pleasae編輯您的問題並添加引用代碼的輸出 –

+0

請參閱'SimpleDateFormat'文檔:https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – RobAu

+0

DateFormat formatter = new SimpleDateFormat(「EEE,dd MMM yyyy HH:mm:ss z」); –

回答

3

什麼是這樣Tue, 08 Dec 2015 06:13:40 GMT格式?有沒有標準或名稱?

The doc of Date.parse()是指其爲「IETF標準日期語法」。作爲「RFC 1123/RFC 822」的That of DateTimeFormatter.RFC_1123_DATE_TIME。後者更新,所以可能更新。

我怎樣才能得到Java的這種格式?

它內置的java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME。例如,在我的電腦上OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME)剛生產

Thu, 6 Apr 2017 15:25:44 +0200 

我用的都是在java.time包中的類。它們是使用我正在使用的Java 8構建的。在Android上,您可以在the ThreeTenABP中獲得java.time課程。

的區在上述輸出偏移是+0200。如果我想要它是GMT?只需使用OffsetDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.RFC_1123_DATE_TIME)即可。更一般地說,請確保您的OffsetDateTime處於UTC偏移量。或者,使用DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC);這將覆蓋您的OffsetDateTime的區域。

如果你不想在ThreeTenABP依賴去做,相信扎基帕坦的評論讓你的Android解決方案。

+0

'java.time.DateTimeFormatter'應該是'java.time.format.DateTimeFormatter' – wener

+0

@wener堆棧溢出邀請您編輯答案來自己做出這樣的更正。我已經做了。 –

+0

謝謝,兩者,爲更正。 –

1

您應該使用SimpleDateFormat類。通過正確的模式,你可以得到任何你想要誠實的輸出。 沒有爲函數文檔,你應該參考 Java Doc Simple Date Format