lito
lito

Reputation: 989

Joda time parse different datetime format

I have the next string: 2000-01-01T01:01:01 and 2000-01-01T01:01:01.000Z Is it possible use ISODateTimeFormat for parse both dates?

Upvotes: 3

Views: 218

Answers (1)

Meno Hochschild
Meno Hochschild

Reputation: 44061

You can use dateTimeParser(). Its description promises:

It accepts formats described by the following syntax: 
 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]]])

Test:

    String s1 = "2000-01-01T01:01:01.000Z";
    String s2 = "2000-01-01T01:01:01";

    DateTime dt1 = ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(s1);
    System.out.println(dt1); // 2000-01-01T01:01:01.000Z

    DateTime dt2 = ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(s2);
    System.out.println(dt2); // 2000-01-01T01:01:01.000+01:00 (using default zone)

Of course, the string without offset is somehow dubious. YOU decide how to interprete the result resp. in which time zone because this information is missing in some parts of your text input.

Personally, I wished Joda-Time offers a possibility to give preference to parsed offset information, but choosing a user-defined time zone offset in case the text input does not have an offset (Joda-Time only allows to set a user-defined zone via formatter.withZone(...) which will be preferred to any available offset information in text input - not ideal).

Upvotes: 3

Related Questions