How to get Zone with the new DateTime API in Java 8

With the new API, I can have a local date and time:

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);

I can also use ZoneId if I need to convert the time to a specific time zone:

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);

I can get the current time:

Instant currentTime = Instant.now();

My question is. Is it possible to get the definition of ZoneId and the definition of the digit (for example, +04: 00) of the current time that is used on the client machine with this new API

+4
source share
2 answers

You can use ZoneId.systemDefault(). Here is the documentation .

+4
source

To get the difference in seconds or hours between GMT and the current time zone, I can use:

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
0

Source: https://habr.com/ru/post/1696269/


All Articles