1
votes

I am using Joda API to format current time (the result must be a string formatted as "yyyy-MM-dd HH:mm:ss"). Below I provide my code and the error message:

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dt = new DateTime();
String datetime = dtf.parseDateTime(dt.toString()).toString();

Error message:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Invalid format: "2014-11-17T11:47:29.229+01:00" is malformed at "T11:47:29.229+01:00" at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:899)

2

2 Answers

4
votes

If you want to convert to string using a custom format do

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dt = new DateTime();
String datetime = dtf.print(dt);

What you're currently doing in the last line is

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:..

So you're converting to & from string several times but never using dtf to actually format how the string should look like.

3
votes

The default DateTime string representation needs a different pattern:

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

If you want to format the date with your pattern you need to use the print() method:

   DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
   DateTime dt = new DateTime();
   String datetime = dtf.print(dt);