How is it possible in Java to convert an instance of java.util.TimeZone
to org.joda.DateTimeZone
and keeping the daylight saving time?
Adjusting Time Zone Use 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.
Joda-Time is the most widely used date and time processing library, before the release of Java 8. Its purpose was to offer an intuitive API for processing date and time and also address the design issues that existed in the Java Date/Time API.
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.
Java 8 and Beyond TimeZone Conversion Example to convert the current date and time to one timezone to another timezone. Step 1: Create current date and time using ZonedDateTime.now () method. Step 2: Create a timezone for Los Angeles using ZoneId.of () method.
DateTime dateTime = new DateTime (date.getTime (), dtz); To Convert from Joda Time of Date to Java Date: For the reverse case Joda DateTime has a method toDate () which will return the java.util Date. DateTime jodaDate = new DateTime (); java.util.Date date = jodaDate.toDate ();
With DateTime you can convert to a Date without specifying the time zone, but to convert from Date to DateTime you should specify the time zone, or it will use the system default time zone. (If you really want that, I'd specify it explicitly to make it clear that it's a deliberate choice.)
Time zone data is provided by the public IANA time zone database. The following table shows all the time zones supported by Joda-Time, using version 2018g of the database. It is also possible to update to a later version of the database.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
java.time.ZoneId
The modern replacement for java.util.TimeZone
is java.time.ZoneId
& java.time.ZoneOffset
.
You should avoid the old legacy date-time classes. But if necessary, you can convert to/from the java.time types. Look to new methods added to the old classes. You can move between TimeZone
and ZoneId
.
java.util.TimeZone tz = java.util.TimeZone.getTimeZone( myZoneId );
…and…
java.time.ZoneId z = myLegacyTimeZone.toZoneId();
If you are looking for the offset-from-UTC or Daylight Saving Time (DST) info for the zone, look at the ZoneRules
class. Search Stack Overflow for more discussion and examples on that, or edit your Question to describe more about your goal.
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