Jodatime malformation even if it looks correct

Viewed 311

I have this piece of code

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss Z");
DateTime dateNow = dtf.parseDateTime(new DateTime().toString());
String registerDateStr = dateNow.toString();

But when I run it, it says malformed date:

java.lang.IllegalArgumentException: Invalid format: "2019-06-13T17:57:47.420+08:00" is malformed at ".420+08:00"

The date formed seems correct to me? Did I do something wrong with the format?

3 Answers

Your format doesn't specify the milliseconds and there's an unneeded space before the timezone information.

This format will work:

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

Shouldn't the result be

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

From the javadoc,

Symbol         Meaning                     Presentation      Examples  
------      -------                     ------------      -------

   H       hour-of-day (0-23)          number            0
   m       minute-of-hour              number            30
   s       second-of-minute            number            55
   S       fraction-of-second          fraction          978

Your format yyyy-MM-dd'T'HH:mm:ss Z didn't work because, you left out S (fraction of second, which is present in your string as .420)

You’re working too hard. You don’t need any explicit formatter at all.

    DateTime dateNow = new DateTime();
    String registerDateStr = dateNow.toString();

    System.out.println(registerDateStr);

Output when I ran just now:

2019-06-13T13:04:48.301+02:00

If you want, you can also parse the string back without a formatter, but I see no reason why you should since you will just get a DateTime object equal to the one you started out from:

    DateTime parsedBack = DateTime.parse(registerDateStr);
    System.out.println(parsedBack);

2019-06-13T13:04:48.301+02:00

Were you aware?

Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).

Quoted from the Joda-Time home page

Related