Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a timezone with org.joda.time?

Tags:

java

jodatime

I want to parse a string into DateTime object:

DateTimeFormatter fmt = DateTimeFormat.forPattern("M/d/yyyy HH:mm");
DateTime dt = fmt.parseDateTime(stringDate + " " +     stringTime).withZone(DateTimeZone.forID("Europe/Dublin"));

If I introduce time 06/22/2014 10:43 I get

06/22/2014 8:43 +0100,

but I want to get

06/22/2014 10:43 +0100

How can I do this?

like image 255
Filosssof Avatar asked Jun 23 '14 13:06

Filosssof


People also ask

How do I change the timezone in Joda DateTime?

Timezone conversionforID( "Asia/Kolkata" ); DateTimeZone timeZoneNewYork = DateTimeZone. forID( "America/New_York" ); DateTime nowLondon = DateTime. now( timeZoneLondon ); // Assign a time zone rather than rely on implicit default time zone. DateTime nowKolkata = nowLondon.

Does Joda DateTime have timezone?

An interval in Joda-Time represents an interval of time from one instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.

What is org Joda-time?

Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.

Is Joda-time followed in Java 8?

Joda-Time provides a quality replacement for the Java date and time classes. Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java. time (JSR-310).


2 Answers

You should apply the timezone to the formatter, not to the DateTime. Otherwise, the date will have been parsed already in your local timezone, and you're merely transposing it to your desired timezone.

DateTimeFormatter fmt = DateTimeFormat.forPattern("M/d/yyyy HH:mm")
                        .withZone(DateTimeZone.forID("Europe/Dublin"));
DateTime dt = fmt.parseDateTime("06/22/2014 10:43");
like image 177
Erwin Bolwidt Avatar answered Sep 20 '22 22:09

Erwin Bolwidt


Look at this extended code:

String s = "06/22/2014 10:43";
DateTimeFormatter fmt = DateTimeFormat.forPattern("M/d/yyyy HH:mm"); // uses local zone
DateTime dt1 = fmt.parseDateTime(s).withZone(DateTimeZone.forID("Europe/Dublin"));
DateTime dt2 = fmt.withZone(DateTimeZone.forID("Europe/Dublin")).parseDateTime(s);
DateTime dt3 =
  fmt.parseDateTime(s).withZoneRetainFields(DateTimeZone.forID("Europe/Dublin"));
System.out.println(dt1); // 2014-06-22T09:43:00.000+01:00 (from my zone Berlin to Dublin)
System.out.println(dt2); // 2014-06-22T10:43:00.000+01:00
System.out.println(dt3); // 2014-06-22T10:43:00.000+01:00
like image 30
Meno Hochschild Avatar answered Sep 19 '22 22:09

Meno Hochschild