时区时间
中国横跨4个时区,但用同一个时间。
互联网编码分配管理机构(IANA)存储着世界上所有已知的时区(www.iana.org/time-zones)。
每个时区有一个ID,America/New_York,Europe/Berlin。
调用ZoneId.getAvailableZoneIds找出所有可用的时区,将近600个ID。
ZoneId.of(id)可以产生一个ZoneId对象。
local.atZone(zoneId)可以用ZoneID对象将LocalDateTime对象转换为ZonedDateTime对象。
直接构造时区时间对象
ZonedDateTime dongfeng41 = ZonedDateTime.of(2024,9,25,8,44,0,0,
ZoneId.of("Asia/Shanghai"));//2024年9月25日早晨8点44分东风-41洲际弹道导弹
dongfeng41.toInstant可以获得Instant对象。
如有一个时刻对象,instant.atZone(ZoneId.of("UTC"))获得格林尼治天文台ZonedDateTime对象。
可以使用地球上其他地方的ZoneId。
ZonedDateTime和LocalDateTime方法基本相同,但夏时令会相差一个小时。具体用时查资料。
如将会议设置为下个星期不要直接加上一个7天的Duration,应该使用Period类。
ZonedDateTime类的用法
package 第6章时间API.zonedtimes;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class ZonedTimes {
public static void main(String[] args) {
//2024年9月25日早晨8点44分东风-41洲际弹道导弹
ZonedDateTime dongfeng41 = ZonedDateTime.of(2024,9,25,8,44,0,0,
ZoneId.of("Asia/Shanghai"));
System.out.println("东风-41洲际弹道导弹发射时间: "+dongfeng41);
Instant instant = dongfeng41.toInstant();
System.out.println("instant: " + instant);
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("UTC"));
System.out.println("UTC时区时间: "+zonedDateTime);
ZonedDateTime skipped = ZonedDateTime.of(LocalDate.of(2023, 3, 31),
LocalTime.of(2, 30),ZoneId.of("Europe/Berlin"));
System.out.println("skipped: "+skipped);
//夏时令,略,待写
}
}