Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java8中使用新的DateTime API获取区域_Java_Datetime_Timezone - Fatal编程技术网

如何在Java8中使用新的DateTime API获取区域

如何在Java8中使用新的DateTime API获取区域,java,datetime,timezone,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); 如果需要

使用新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)?

您可以使用
ZoneId.systemDefault()

.

要获得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
然而,亚历山大的方式似乎更优雅:

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


伟大的非常感谢。请您提供如何获取ZoneId的数字定义(如+04:00)以获得完整答案。在本例中,请使用
ZoneId.systemDefault().getRules().getOffset(Instant.now())但您应该知道此偏移量取决于当前时间(夏令时等)
System.out.println("Offset: " + ZoneId.systemDefault().getRules().getOffset(Instant.now()));//+03:00