Java Reference
In-Depth Information
.toFormatter(Locale.ITALIAN);
So far you've learned how to create, manipulate, format, and parse both points in time and
intervals. But you haven't seen how to deal with subtleties involving dates and time. For
example, you may need to deal with different time zones or work with alternative calendar
systems. In the next sections, we explore these topics using the new Date and Time API.
12.3. Working with different time zones and calendars
None of the classes you've seen so far contained any information about time zones. Dealing with
time zones is another important issue that's been vastly simplified by the new Date and Time
API. The new java.time.ZoneId class is the replacement for the old java.util.TimeZone class. It
aims to better shield you from the complexities related to time zones, such as dealing with
Daylight Saving Time (DST). Like the other classes of the Date and Time API, it's immutable.
A time zone is a set of rules corresponding to a region in which the standard time is the same.
There are about 40 of them held in instances of the ZoneRules class. You can simply call
getRules() on a ZoneId to obtain the rules for that given time zone. A specific ZoneId is
identified by a region ID, for example:
ZoneId romeZone = ZoneId.of("Europe/Rome");
The region IDs are all in the format “{area}/{city}” and the set of available locations is the one
supplied by the IANA Time Zone Database. You can also convert an old TimeZone object to a
ZoneId by using the new method toZoneId:
ZoneId zoneId = TimeZone.getDefault().toZoneId();
Once you have a ZoneId object, you can combine it with a LocalDate, a LocalDateTime, or an
Instant, to transform it into ZonedDateTime instances, which represent points in time relative
to the specified time zone, as shown in the next listing.
Listing 12.13. Applying a time zone to a point in time
LocalDate date = LocalDate.of(2014, Month.MARCH, 18);
ZonedDateTime zdt1 = date.atStartOfDay(romeZone);
LocalDateTime dateTime = LocalDateTime.of(2014, Month.MARCH, 18, 13, 45);
ZonedDateTime zdt2 = dateTime.atZone(romeZone);
 
Search WWH ::




Custom Search