Reputation: 3228
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"
Upvotes: 1
Views: 5459
Reputation: 479
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);
Upvotes: 2
Reputation: 7496
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
Upvotes: 1