2014-11-17 30 views
0

我使用Joda API格式化當前時間(結果必須是格式爲「yyyy-MM-dd HH:mm:ss」的字符串)。下面我提供我的代碼和錯誤消息:喬達時間:格式無效

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 
DateTime dt = new DateTime(); 
String datetime = dtf.parseDateTime(dt.toString()).toString(); 

錯誤消息:

異常在線程 「AWT-EventQueue的 - 0」 java.lang.IllegalArgumentException異常:無效的格式: 「2014- 11-17T11:47:29.229 + 01:47:29.229 + 01:00" T11在格式錯誤 「00」 在 org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:899)

回答

2

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+01:00'"); 

如果您想格式化你的模式,你需要使用打印日期()方法使用自定義格式字符串做

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 
DateTime dt = new DateTime(); 
String datetime = dtf.print(dt); 

你目前做的最後一行是什麼

String defaultFormatted = dt.toString(); 
// this is what contains the "T11:47:29.229+01:00" part 

DateTime dateTime = dtf.parseDateTime(defaultFormatted); 
// we're back at the beginning, this is equivalent to your original "dt" 

String defaultFormattedAgain = dateTime.toString(); 
// and this is the same as the initial string with T11:.. 

所以你從字符串轉換爲&幾次,但從來沒有使用dtf實際格式化字符串應該是什麼樣子等。

3

默認的DateTime字符串表示需要一個不同的模式:如果要轉換

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 
    DateTime dt = new DateTime(); 
    String datetime = dtf.print(dt); 
+0

謝謝。但是,如何生成當前日期和時間,然後將其格式設置爲「yyyy-MM-dd HH:mm:ss」? –

+0

添加回答。 – BarrySW19