如何在Java 8中使用新的DateTime API获取Zone

时间:2018-04-18 08:31:08

标签: java datetime timezone

使用新API我可以拥有本地日期和时间:

LocalTime localTime = LocalTime.of(9,0,0);
LocalDate localDate = LocalDate.of(2017, Month.JUNE, 3);
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
System.out.println("LocalDateTime:" + localDateTime);

如果我需要将时间转换为特定时区,我也可以使用ZoneId:

ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("GMT"));
System.out.println("ZonedDateTime: " + zonedDateTime);

ZonedDateTime zonedDateTime2 = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/London"));
System.out.println("ZonedDateTime London: " + zonedDateTime2);

我可以通过以下方式获得当前时间:

Instant currentTime = Instant.now();

我的问题。是否可以通过此新API获取客户机上使用的当前时间的 ZoneId和数字定义(如+04:00) ?

2 个答案:

答案 0 :(得分:4)

您可以使用ZoneId.systemDefault()Here is documentation

答案 1 :(得分:0)

要获得GMT和当前时区之间的秒数或小时差异,我可以使用:

ZonedDateTime zonedDateTimeCurrent = ZonedDateTime.of(LocalDateTime.now(), ZoneId.systemDefault());
ZonedDateTime zonedDateTimeGMT = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("GMT"));
Duration timeZoneDifferenceDuration = Duration.between(zonedDateTimeCurrent, zonedDateTimeGMT);

System.out.println("TimeZoneDifference in seconds: " + timeZoneDifferenceDuration.getSeconds());

Double hours = (double)timeZoneDifferenceDuration.getSeconds()/(60*60);
System.out.println("TimeZoneDifference in hours: " + hours);//3.0 //4.5 //-5.0
然而,Alexanders的方式看起来更优雅:

  

ZoneId.systemDefault()getRules()的getOffset(Instant.now());

System.out.println("Offset: " + ZoneId.systemDefault().getRules().getOffset(Instant.now()));//+03:00