Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda time parse different datetime format

Tags:

java

jodatime

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?

like image 797
lito Avatar asked Sep 01 '26 17:09

lito


1 Answers

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

like image 169
Meno Hochschild Avatar answered Sep 03 '26 07:09

Meno Hochschild



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!