How can I parse a date including timezone with Joda Time
JavaDatetimeTimezoneJodatimeJava Problem Overview
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?
Java Solutions
Solution 1 - Java
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.
Solution 2 - Java
also you can chose:
// parse using the Paris zone
DateTime date = formatter.withZone(DateTimeZone.forID("Europe/Paris")).parseDateTime(str);
Solution 3 - Java
java.time
Quoted below is a notice from the home page of Joda-Time:
> Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Do not use a fixed text for the timezone:
Do not use a fixed text (e.g. 'GMT'
) for the timezone as you have done because that approach may fail for other locales.
Solution using java.time
, the modern Date-Time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "Mon Aug 24 12:36:46 GMT+1000 2009";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("E MMM d H:m:s VVZ u", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, parser);
System.out.println(odt);
// Custom fromat
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
System.out.println(formatter.format(odt));
}
}
Output:
2009-08-24T12:36:46+10:00
2009-08-24T12:36:46.000+10:00
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.