The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
A time zone is a region of the earth where the same standard time is used. 时区是地球上使用相同标准时间的区域。Each time zone is described by an identifier and usually has the format region/city (Asia/Tokyo) and an offset from Greenwich/UTC time. 每个时区都由一个标识符描述,通常具有region/city
(Asia/Tokyo)格式和格林威治/UTC时间的偏移量。For example, the offset for Tokyo is +09:00.例如,东京的偏移量为+09:00。
The Date-Time API provides two classes for specifying a time zone or an offset:日期-时间API提供了两个用于指定时区或偏移的类:
Offsets from Greenwich/UTC time are usually defined in whole hours, but there are exceptions. 格林威治/UTC时间的偏移量通常以整小时为单位定义,但也有例外。The following code, from the TimeZoneId example, prints a list of all time zones that use offsets from Greenwich/UTC that are not defined in whole hours.下面的代码来自TimeZoneId示例,它打印使用格林威治/UTC偏移量的所有时区的列表,这些偏移量未在整小时内定义。
Set<String> allZones = ZoneId.getAvailableZoneIds(); LocalDateTime dt = LocalDateTime.now(); // Create a List using the set of zones and sort it. List<String> zoneList = new ArrayList<String>(allZones); Collections.sort(zoneList); ... for (String s : zoneList) { ZoneId zone = ZoneId.of(s); ZonedDateTime zdt = dt.atZone(zone); ZoneOffset offset = zdt.getOffset(); int secondsOfHour = offset.getTotalSeconds() % (60 * 60); String out = String.format("%35s %10s%n", zone, offset); // Write only time zones that do not have a whole hour offset // to standard out. if (secondsOfHour != 0) { System.out.printf(out); } ... }
This example prints the following list to standard out:此示例将以下列表打印到标准输出:
America/Caracas -04:30 America/St_Johns -02:30 Asia/Calcutta +05:30 Asia/Colombo +05:30 Asia/Kabul +04:30 Asia/Kathmandu +05:45 Asia/Katmandu +05:45 Asia/Kolkata +05:30 Asia/Rangoon +06:30 Asia/Tehran +04:30 Australia/Adelaide +09:30 Australia/Broken_Hill +09:30 Australia/Darwin +09:30 Australia/Eucla +08:45 Australia/LHI +10:30 Australia/Lord_Howe +10:30 Australia/North +09:30 Australia/South +09:30 Australia/Yancowinna +09:30 Canada/Newfoundland -02:30 Indian/Cocos +06:30 Iran +04:30 NZ-CHAT +12:45 Pacific/Chatham +12:45 Pacific/Marquesas -09:30 Pacific/Norfolk +11:30
The TimeZoneId example also prints a list of all time zone IDs to a file called TimeZoneId示例还将所有时区ID的列表打印到名为timeZones的文件中。timeZones
.
The Date-Time API provides three temporal-based classes that work with time zones:Date-Time API提供了三个基于时间的类,它们与时区一起工作:
When would you use OffsetDateTime instead of ZonedDateTime? 什么时候使用OffsetDateTime而不是ZoneDateTime?If you are writing complex software that models its own rules for date and time calculations based on geographic locations, or if you are storing time-stamps in a database that track only absolute offsets from Greenwich/UTC time, then you might want to use OffsetDateTime. 如果您正在编写复杂的软件,根据地理位置为自己的日期和时间计算规则建模,或者如果您在数据库中存储时间戳,只跟踪格林威治/UTC时间的绝对偏移量,那么您可能希望使用OffsetDateTime。Also, XML and other network formats define date-time transfer as OffsetDateTime or OffsetTime.此外,XML和其他网络格式将日期时间传输定义为OffsetDateTime或OffsetTime。
Although all three classes maintain an offset from Greenwich/UTC time, only ZonedDateTime uses the ZoneRules, part of the java.time.zone package, to determine how an offset varies for a particular time zone. 尽管这三个类都保持格林威治/UTC时间的偏移量,但只有ZoneDateTime使用java.time.zone包中的ZoneRules来确定特定时区的偏移量如何变化。For example, most time zones experience a gap (typically of 1 hour) when moving the clock forward to daylight saving time, and a time overlap when moving the clock back to standard time and the last hour before the transition is repeated. 例如,将时钟向前移动到夏时制时,大多数时区都会出现间隔(通常为1小时),将时钟向后移动到标准时间和重复转换前的最后一个小时时,会出现时间重叠。The ZonedDateTime class accommodates this scenario, whereas the OffsetDateTime and OffsetTime classes, which do not have access to the ZoneRules, do not.ZoneDateTime类适用于这种情况,而OffsetDateTime和OffsetTime类则不适用于这种情况,它们无权访问ZoneRules。
The ZonedDateTime class, in effect, combines the LocalDateTime class with the ZoneId class. ZonedDateTime类实际上是LocalDateTime类和ZoneId类的组合。It is used to represent a full date (year, month, day) and time (hour, minute, second, nanosecond) with a time zone (region/city, such as Europe/Paris).它用于表示完整的日期(年、月、日)和时间(小时、分钟、秒、纳秒)以及时区(地区/城市,如欧洲/巴黎)。
The following code, from the 以下代码来自Flight
example, defines the departure time for a flight from San Francisco to Tokyo as a ZonedDateTime in the America/Los Angeles time zone. Flight
示例,将从旧金山到东京的航班的起飞时间定义为美国/洛杉矶时区的ZonedDateTime。The withZoneSameInstant and plusMinutes methods are used to create an instance of ZonedDateTime that represents the projected arrival time in Tokyo, after the 650 minute flight. WithZoneSamInstant和plusMinutes方法用于创建ZoneDateTime的实例,该实例表示650分钟飞行后预计到达东京的时间。The ZoneRules.isDaylightSavings method determines whether it is daylight saving time when the flight arrives in Tokyo.ZoneRules.Daylightsavings方法确定航班抵达东京时是否为夏令时。
A DateTimeFormatter object is used to format the ZonedDateTime instances for printing:DateTimeFormatter对象用于格式化ZonedDateTime实例以进行打印:
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a"); // Leaving from San Francisco on July 20, 2013, at 7:30 p.m. LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); ZoneId leavingZone = ZoneId.of("America/Los_Angeles"); ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone); try { String out1 = departure.format(format); System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone); } catch (DateTimeException exc) { System.out.printf("%s can't be formatted!%n", departure); throw exc; } // Flight is 10 hours and 50 minutes, or 650 minutes ZoneId arrivingZone = ZoneId.of("Asia/Tokyo"); ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone) .plusMinutes(650); try { String out2 = arrival.format(format); System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone); } catch (DateTimeException exc) { System.out.printf("%s can't be formatted!%n", arrival); throw exc; } if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant())) System.out.printf(" (%s daylight saving time will be in effect.)%n", arrivingZone); else System.out.printf(" (%s standard time will be in effect.)%n", arrivingZone);
This produces the following output:这将产生以下输出:
LEAVING: Jul 20 2013 07:30 PM (America/Los_Angeles) ARRIVING: Jul 21 2013 10:20 PM (Asia/Tokyo) (Asia/Tokyo standard time will be in effect.)
The OffsetDateTime class, in effect, combines the LocalDateTime class with the ZoneOffset class. OffsetDateTime类实际上将LocalDateTime和ZoneOffset类组合在一起。It is used to represent a full date (year, month, day) and time (hour, minute, second, nanosecond) with an offset from Greenwich/UTC time (+/-hours:minutes, such as +06:00 or -08:00).它用于表示完整的日期(年、月、日)和时间(小时、分钟、秒、纳秒),并与格林尼治/UTC时间(+/-小时:分钟,如+06:00或-08:00)偏移。
The following example uses OffsetDateTime with the TemporalAdjuster.lastDay method to find the last Thursday in July 2013.以下示例使用OffsetDateTime和TemporalAdjuster.lastDay方法查找2013年7月的最后一个星期四。
// Find the last Thursday in July 2013. LocalDateTime localDate = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); ZoneOffset offset = ZoneOffset.of("-08:00"); OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset); OffsetDateTime lastThursday = offsetDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY)); System.out.printf("The last Thursday in July 2013 is the %sth.%n", lastThursday.getDayOfMonth());
The output from running this code is:运行此代码的输出为:
The last Thursday in July 2013 is the 25th.
The OffsetTime class, in effect, combines the LocalTime class with the ZoneOffset class. 实际上,OffsetTime类将LocalTime类与ZoneOffset类相结合。It is used to represent time (hour, minute, second, nanosecond) with an offset from Greenwich/UTC time (+/-hours:minutes, such as +06:00 or -08:00).它用于表示时间(小时、分钟、秒、纳秒),与格林尼治/UTC时间(+/-小时:分钟,如+06:00或-08:00)有偏移。
The OffsetTime class is used in the same situations as the OffsetDateTime class, but when tracking the date is not needed.OffsetTime类在与OffsetDateTime类相同的情况下使用,但不需要跟踪日期。