2014-07-10 46 views
1

如何使用joda time API將「2014-06-16T07:00:00.000Z」轉換爲「16-JUN-14 07:00:00」?喬達時間轉換查詢

下面的代碼拋出異常

java.lang.IllegalArgumentException: Illegal pattern component: T 
    at org.joda.time.format.DateTimeFormat.parsePatternTo(DateTimeFormat.java:570) 
    at org.joda.time.format.DateTimeFormat.createFormatterForPattern(DateTimeFormat.java:693) 
    at org.joda.time.format.DateTimeFormat.forPattern(DateTimeFormat.java:181) 
    at com.joda.JodaTimeTest.convertJodaTimezone(JodaTimeTest.java:59) 
    at com.joda.JodaTimeTest.main(JodaTimeTest.java:50) 

這是代碼:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-ddTHH:mm:ssZ"); 
    DateTime dt = formatter.parseDateTime(dstDateTime.toString()); 

回答

4

您需要附上文字T單引號內。此外,毫秒的圖案不正確。您需要包含毫秒內的SSS。有關更多信息,請參閱patterns here

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 

更新:要將DateTime格式化成您所選擇的字符串表示,你需要做到這一點。

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
DateTime dt = formatter.parseDateTime(dstDateTime.toString()); // You get a DateTime object 

// Create a new formatter with the pattern you want 
DateTimeFormatter formatter2 = DateTimeFormat.forPattern("dd-MMM-yy HH:mm:ss"); 
String dateStringInYourFormat = formatter2.print(dt); // format the DateTime to that pattern 
System.out.println(dateStringInYourFormat); // Prints 16-Jun-14 12:30:00 because of the TimeZone I'm in 

既可以自己指定時區,也可以指定您的默認系統時區。

+0

謝謝你的更新,但得到這個異常java.lang.IllegalArgumentException:無效的格式:「2014-06-16T07:00:00.000Z」格式錯誤在「.000Z」 – user3157090

+0

現在它工作正常,但小問題,輸出是添加「-07:00」在2014-06-16T00:00:00.000-07:00結束,我不需要它。如何解決它? – user3157090

1

您需要更改

"yyyy-MM-ddTHH:mm:ssZ" 

"yyyy-MM-dd'T'HH:mm:ss.SSS'Z" 

現在

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z"); 
DateTime dt = formatter.parseDateTime("2014-06-16T07:00:00.000Z"); 
System.out.println(dt); 

輸出:

2014-06-16T07:00:00.000+05:30 
+0

感謝您的更新,但得到此異常java.lang.IllegalArgumentException:格式無效:「2014-06-16T07:00:00.000Z」在「.000Z」格式不正確 – user3157090