3

I'm using joda time to format my ISO Date input string, but I'm getting an exception that my ISO Date is malformed:

Invalid format: "2014-06-20T11:41:08+02:00" is malformed at "+02:00"

This is my code:

val formatter: DateTimeFormatter = ISODateTimeFormat.dateTime.withZone(DateTimeZone.getDefault)
val date: DateTime = formatter.parseDateTime("2014-06-20T11:41:08+02:00")

What's wrong here?

pichsenmeister
  • 2,132
  • 4
  • 18
  • 34
  • 2
    The data format string is "yyyyMMdd'T'HHmmss.SSSZ". Hence you need a dot (".") and three digits between the seconds and the time zone. The three digits are mandatory and represent the milliseconds. – stefan.schwetschke Jun 20 '14 at 10:03

2 Answers2

7

The error comment is slightly misleading here, as Joda formatter you derive from ISODateTimeFormat expects the millisecond part of the date/time string to be present, therefore the following will work fine:

val formatter: DateTimeFormatter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.getDefault())
val date: DateTime = formatter.parseDateTime("2014-06-20T11:41:08.0+02:00")
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
Norbert Radyk
  • 2,608
  • 20
  • 24
4

The answer by Radyk is correct.

ISO 8601 Formats Built-In

However, you needn't specify a formatter at all. The DateTime class has a built-in parser for your ISO 8601 compliant format, used automatically by the constructor.

DateTime dateTime = new DateTime( "2014-06-20T11:41:08+02:00", timeZone );

While the second argument is optional, I suggest you assign a DateTimeZone object to be assigned to the DateTime if you know such a time zone. The input string has an offset-from-UTC, but a time zone is more than just an offset. A time zone includes rules for Daylight Saving Time and other anomalies. Use proper time zone names, never 3 or 4 letter codes like EST or IST.

Other Formats

You can apply many other formats:

For example, if you want only the date portion without the time-of-day in your String representation, call ISODateTimeFormat.date() to access a built-in formatter.

Example code in Joda-Time 2.8.

String output = ISODateTimeFormat.date().print( dateTime );  // Format: yyyy-MM-dd

Search StackOverflow for hundreds of other Questions and Answers about formatting date-time values.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • thanks for your answer. is there a way to print exactly this format with joda datetime? – pichsenmeister Jun 20 '14 at 10:22
  • 2
    The same built-in formatter is used by default in a DateTime's `toString` method. `String output = dateTime.toString();` if you want Strings generated in other formats, explore the `DateTimeFormat` class including the `forPattern` and `forStyle` methods and ISODateTimeFormat subclass. – Basil Bourque Jun 20 '14 at 17:11