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

5

使用新的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,是否可以获取客户端机器上当前使用的时区ID和数字定义(例如+04:00)?

2个回答

6
你可以使用ZoneId.systemDefault()。这里有关于它的文档

太好了。非常感谢你。 - Kirill Ch
请问您能否提供如何获取ZoneId的数字定义(例如+04:00)的完整答案。 - Kirill Ch
1
在这种情况下,使用ZoneId.systemDefault().getRules().getOffset(Instant.now());。但是您应该知道,此偏移量取决于当前时间(夏令时等)。 - Alexander Terekhov

0

要获取格林威治标准时间和当前时区之间的秒数或小时数,可以使用:

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

然而,亚历山大的方法似乎更加优雅:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接