2014-11-17 32 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