2015-10-26 90 views
0

我怎麼能轉換日期格式 「2015年10月26日20:07:45 + 00」轉換日期爲UTC與+00

如果我使用UTC-「YYYY-MM-dd'T'HH :mm:ss'Z'「,我得到」2015-10-26T20:07:45Z「

我應該簡單地用空格替換T還是用+00替換Z,或者我可以使用任何其他格式來獲得我直接想要的格式?

TimeZone tz = TimeZone.getTimeZone("UTC"); 
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); 
df.setTimeZone(tz); 
String nowAsISO = df.format(now); 
+0

是什麼你的意見?現在是什麼? – AbtPst

+1

您是否檢查了[SimpleDateFormat的文檔](http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)的答案? – VGR

回答

0

DateFormat的DF =新的SimpleDateFormat( 「YYYY-MM-dd'T'HH:MM:SSZ」);

0

根據SimpleDateFormat的文檔,不存在將ISO-UTC偏移顯示爲「+00」的圖案符號。最接近的模式符號是「X」,只有當時區偏移量偏離UTC時才顯示小時偏移量。因此,我認爲主要有兩個選項:

TimeZone tz = TimeZone.getTimeZone("UTC"); 
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'+00'"); 
df.setTimeZone(tz); 
String nowAsISO = df.format(new Date()); 
System.out.println(nowAsISO); 

設置文字偏移這裏(異常),因爲你明確地設置的格式對象的時區UTC仍然沒有問題。但它仍然是一個黑客。

否則,你可以使用(如果Java 8 - 使用新格局符號 「X」):

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssx"); 
ZonedDateTime zdt = ZonedDateTime.now(ZoneOffset.UTC); 
String nowAsISO = dtf.format(zdt); 
System.out.println(nowAsISO); // 2015-10-27 18:13:15+00 

替代 - 恕我直言更好 - 在Java的8路:

DateTimeFormatter dtf = 
    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssx").withZone(ZoneOffset.UTC); 
Instant now = new Date().toInstant(); // or better: Instant.now(); 
String nowAsISO = dtf.format(now); 
System.out.println(nowAsISO); // 2015-10-27 18:13:15+00