Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Zone off by 10 hours in Joda-Time

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?

like image 689
Eddy Avatar asked Jan 24 '26 14:01

Eddy


1 Answers

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, a DateTime is not a string nor does it contain a string. A DateTimeFormatter instance can generate a string representation of the date, time, and time zone information stored within a DateTime. When you invoke the toString method on a DateTime (either implicitly or explicitly), a built-in formatter based on ISO 8601 is used automatically. That formatter uses YYYY-MM-DDTHH:MM:SS.ssssss+00:00 format.

like image 126
nhahtdh Avatar answered Jan 26 '26 02:01

nhahtdh



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!