0
votes

I am trying to convert the date entered by my app user as String to ISO 8601 format using Joda-Time, so I am using the following code but I get error:

String oldDate = "05/05/2013";
DateTime oldD = DateTime.parse(oldDate);
DateTimeFormatter OldDFmt = ISODateTimeFormat.dateTime();
String str = OldDFmt.print(oldD);
System.out.println(str);

but I am always getting error:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Invalid format: "05/05/2013" is malformed at "/05/2013"

Can someone please help and tell me what I am doing wrong here? Thanks.

2
When reading exceptions like that, the hint is usually in the message. There was a problem parsing "/05/2013", which is a bit of your oldDate variable. - Paul Hicks

2 Answers

5
votes

Can someone please help and tell me what I am doing wrong here?

The error occurs here.

DateTime oldD = DateTime.parse(oldDate);

The DateTime.parse(String) method parses your String argument using a ISODateTimeFormat.dateTimeParser().

The format must be of the form

 datetime          = time | date-opt-time
 time              = 'T' time-element [offset]
 date-opt-time     = date-element ['T' [time-element] [offset]]
 date-element      = std-date-element | ord-date-element | week-date-element
 std-date-element  = yyyy ['-' MM ['-' dd]]
 ord-date-element  = yyyy ['-' DDD]
 week-date-element = xxxx '-W' ww ['-' e]
 time-element      = HH [minute-element] | [fraction]
 minute-element    = ':' mm [second-element] | [fraction]
 second-element    = ':' ss [fraction]
 fraction          = ('.' | ',') digit+
 offset            = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])

which yours

String oldDate = "05/05/2013";

isn't.

You'll need to parse your String date with a parser with a corresponding format, like what Paul Hicks is suggesting. You can then format the created DateTime into the ISO standard format.

4
votes

The formatter you're using to parse the string DateTime.parse(oldDate) is the default one: according to the javadocs, ISODateTimeFormat.dateTimeParser(). You want a parsing DateTimeFormatter that knows about your string format dd/mm/yyyy. I don't use joda-time, but I think you want this:

DateTimeFormatter stringParser = DateTimeFormat.forPattern("dd/MM/yyyy");

The rest of the code looks ok.