Joda DateTime Invalid format

余生长醉 提交于 2019-12-12 01:22:41

问题


I'm trying to get the current DateTime with my DateTimeFormat pattern, but i'm getting the exception...

//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());

I'm getting this exception, I cannot understand who is giving the malformed format

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

回答1:


This line DateTime now = dtf.parseDateTime(currentDate.toString()); isn't correct because you try parse date with default toSring format. You have to parse string which formatted the same way as 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);



回答2:


You are using the wrong format to parse the date. If you print out the date you are trying to parse after converting it to a String with toString you get:

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

This date string does not conform to the pattern dd/MM/YYYY HH:mm. To parse the to a string converted currentDate to a DateTime object again, you have to use the following pattern:

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

Parsing with this DateTimeFormatter will get you another instance that represents the same time as the original currentDate.

For more details on the DateTimeFormatter and it's parsing options check out the JavaDoc



来源:https://stackoverflow.com/questions/41465000/joda-datetime-invalid-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!