Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a date including timezone with Joda Time

This snippet of code always parses the date into the current timezone, and not into the timezone in the string being parsed.

final DateTimeFormatter df = DateTimeFormat         .forPattern("EEE MMM dd HH:mm:ss 'GMT'Z yyyy"); final DateTime dateTime = df         .parseDateTime("Mon Aug 24 12:36:46 GMT+1000 2009"); System.out.println("dateTime = " + dateTime); // outputs dateTime = 2009-08-24T04:36:46.000+02:00 

It outputs:

dateTime = 2009-08-24T04:36:46.000+02:00 

whereas I expect:

dateTime = 2009-08-24T04:36:46.000+10:00 

Any ideas what I'm doing wrong?

like image 840
Steve McLeod Avatar asked Aug 25 '09 09:08

Steve McLeod


People also ask

Does Joda DateTime have timezone?

Adjusting Time ZoneUse the DateTimeZone class in Joda-Time to adjust to a desired time zone. Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone). Use proper time zone names.

How do I change the date format in Joda-time?

How to change the SimpleDateFormat to jodatime? String s = "2014-01-15T14:23:50.026"; DateTimeFormatter dtf = DateTimeFormat. forPattern("yyyy-MM-dd'T'HH:mm:ss. SSSS"); DateTime instant = dtf.

What is Joda-time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.

Is Joda-time deprecated?

So the short answer to your question is: YES (deprecated).


1 Answers

OK, further Googling gave me the answer to my own question: use withOffsetParsed(), as so:

final DateTimeFormatter df = DateTimeFormat         .forPattern("EEE MMM dd HH:mm:ss 'GMT'Z yyyy"); final DateTime dateTime = df.withOffsetParsed()         .parseDateTime("Mon Aug 24 12:36:46 GMT+1000 2009"); 

This works.

like image 93
Steve McLeod Avatar answered Sep 22 '22 23:09

Steve McLeod