Joda DateTime格式无效

时间:2017-01-04 13:28:26

标签: java datetime jodatime

我试图用我的DateTimeFormat模式获取当前的DateTime,但我得到了异常...

//sets the current date
DateTime currentDate = new DateTime();
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/YYYY HH:mm").withLocale(locale);
DateTime now = dtf.parseDateTime(currentDate.toString());

我得到这个例外,我无法理解是谁给出了格式错误的格式

java.lang.IllegalArgumentException: Invalid format: "2017-01-04T14:24:17.674+01:00" is malformed at "17-01-04T14:24:17.674+01:00"

2 个答案:

答案 0 :(得分:2)

此行DateTime now = dtf.parseDateTime(currentDate.toString());不正确,因为您尝试使用默认的toSring格式解析日期。你必须解析格式与pattern相同的字符串:

DateTime currentDate = new DateTime();
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/YYYY HH:mm").withLocale(locale);
String formatedDate = dtf.print(currentDate);
System.out.println(formatedDate);
DateTime now = dtf.parseDateTime(formatedDate);
System.out.println(now);

答案 1 :(得分:1)

您使用错误的格式来解析日期。如果在将其转换为包含toString的字符串后打印出您尝试解析的日期,则会得到:

2017-01-04T14:24:17.674+01:00

此日期字符串不符合模式dd/MM/YYYY HH:mm。要再次解析转换为currentDateDateTime对象的字符串,您必须使用以下模式:

DateTimeFormatter dtf = DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm:ss.SSSZ")
                                      .withLocale(locale);

使用此DateTimeFormatter进行解析将获得另一个与原始currentDate代表同一时间的实例。

有关DateTimeFormatter及其解析选项的详细信息,请查看JavaDoc

相关问题