zoneId
// 1、获取系统默认的ZoneId
// JDK 1.8之前做法
Assert.assertEquals("Asia/Shanghai", TimeZone.getDefault().getID());
Assert.assertEquals("GMT+08:00", TimeZone.getTimeZone("GMT+08:00").getID());
Assert.assertEquals("GMT-05:00", TimeZone.getTimeZone("GMT-05:00").getID());
// 查询所有可用的zoneId
Arrays.stream(TimeZone.getAvailableIDs()).forEach(System.out::println);
// JDK 1.8之后做法
Assert.assertEquals("Asia/Shanghai", ZoneId.systemDefault().getId());
Assert.assertEquals("Asia/Shanghai", ZonedDateTime.now().getZone().getId());
// 查询所有可用的zoneId
ZoneId.getAvailableZoneIds().forEach(System.out::println);
// 2、指定字符串得到一个ZoneId
Assert.assertEquals("Asia/Shanghai",ZoneId.of("Asia/Shanghai").getId());
Assert.assertEquals("+09:00",ZoneId.of("+09:00").getId());
Assert.assertEquals("+08:00",ZoneId.of("+8").getId());
Assert.assertEquals("Z",ZoneId.of("+0").getId());
Assert.assertEquals("Z",ZoneId.of("Z").getId());
Assert.assertEquals("UTC",ZoneId.of("UTC").getId());
// 3、根据偏移量得到一个ZoneId
// 根据偏移量得到的ZoneId内部并无现成时区规则可用,因此对于有夏令营的国家转换可能出问题,一般不建议这么去做
Assert.assertEquals("UTC+08:00",ZoneId.ofOffset("UTC", ZoneOffset.of("+8")).getId());
Assert.assertEquals("UTC",ZoneId.ofOffset("UTC", ZoneOffset.of("Z")).getId()); // 必须是大写的Z
// 4、从日期里面获得时区
Assert.assertEquals("Asia/Shanghai",ZoneId.from(ZonedDateTime.now()).getId());
Assert.assertEquals("+08:00",ZoneId.from(ZoneOffset.of("+8")).getId());
//System.out.println(ZoneId.from(LocalDateTime.now()));//报错:java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor:
//System.out.println(ZoneId.from(LocalDate.now()));//报错:java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor:
设置默认时区 参考
API方式:强制将时区设为北京时区
System.out.println(TimeZone.getDefault());
// sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null]
TimeZone timeZone = TimeZone.getTimeZone("GMT+8");
System.out.println(timeZone);
// sun.util.calendar.ZoneInfo[id="GMT+08:00",offset=28800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
TimeZone.setDefault(timeZone);
System.out.println(TimeZone.getDefault());
// sun.util.calendar.ZoneInfo[id="GMT+08:00",offset=28800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
JVM参数方式:
-Duser.timezone=GMT+8