I need to parse a string into a Joda-Time DateTime (or java.util.Date.) This is an example of the string I'm getting:
eventDateStr = 2013-02-07T16:05:54-0800
The code I'm using:
DateTimeFormatter presentation = DateTimeFormat.forPattern("yyyy-MM-dd kk:mm:ssZ");
DateTime eveDate = presentation.parseDateTime(eventDateStr);
The above throws this exception:
Invalid format: "2013-02-07T16:05:54-0800" is malformed at "T04:03:20-0800"
So I'm parsing the 'T' out of there:
eventDateStr = eventDateStr.indexOf("T") > 0 ? eventDateStr.replace("T", " ") : eventDateStr;
and trying again. This time no exception but the time zone is off:
2013-02-08T02:05:54.000+02:00
Note the difference: in the original string the timezone is '-0800' and here it's '+02:00'. This in turn changes the entire date, which is now a day later.
What am I doing wrong?
Call the method withOffsetParsed on the DateTimeFormatter object to get a DateTimeFormatter that keeps the time zone parsed from the String, instead of offsetting it to the local time zone.
Regarding why T is shown when you print out the DateTime, Basil Bourque has a nice explanation in the comment below.
Regarding
T, aDateTimeis not a string nor does it contain a string. ADateTimeFormatterinstance can generate a string representation of the date, time, and time zone information stored within aDateTime. When you invoke thetoStringmethod on aDateTime(either implicitly or explicitly), a built-in formatter based on ISO 8601 is used automatically. That formatter usesYYYY-MM-DDTHH:MM:SS.ssssss+00:00format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With