Java ZonedDateTime - Instant Conversion

I plan to convert ZonedDateTime to instant, as shown below.

Say I'm in PST timeZone and the current time is 11A.M. If I convert now (without daylight from today March 4, 2018), and toInstant will be 7 PM

For the same 11 AM, toInstant will return 6 PM as of April 4, 2018, when daylight saving time will be observed.

So, the code below is returned correctly.

ZonedDateTime dateTime = ZonedDateTime.now();  --->>> March 04th 2018 at 11 A.M PST
dateTime.plusMonths(1).toInstant(); -->> returns April 04th 2018 at 6 PM PST as daylight saving will be observed

But,

The result will be different if I convert to Instant and then add a month.

Instant dateTime = ZonedDateTime.now().toInstant();  --->>> March 04th 2018 at 7 P.M UTC
dateTime.plus(1,ChronoUnit.MONTHS).toInstant(); -->> returns April 04th 2018 at 7 PM UTC ( but the actual time should be 6 PM UTC ). 

This is normal, as we have already converted to UTC, and it just adds from there.

Therefore, to enable daylight saving time, I need to add days, months or years .... to ZonedDateTime, and then convert to Instant.

ZonedDateTime dateTime = ZonedDateTime.now();   ---> March 04th 2018 at 11A.M
dateTime.plusDays(10).toInstant();     ---> March 14th 2018 at 6P.M
dateTime.plusMonths(1).toInstant();     ---> April 04th 2018 at 6P.M

, . 6 P.M, 7 P.M.

dateTime.plusSeconds(org.joda.time.Period.days(1).multipliedBy(10).toStandardSeconds().getSeconds())
         .toInstant())  --> ---> March 14th 2018 at 7P.M

, .

+4
2

ZonedDateTime. plusDays :

, -. ZonedDateTime, , .

ZonedDateTime, - , , , . - .

plusSeconds :

, . , - , . , , , .

, , -, , .

+3

, , ,

    long minutesToAdd = Duration.ofDays(10).toMinutes();

java.time, Joda-Time. , Joda-Time, .

, , . , 10 . , 9 , 9 10 . , LocalDateTime, , ZonedDateTime.

    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
    System.out.println(now);
    System.out.println(now.toInstant());
    Instant inTenDays = now.toLocalDateTime()
            .plusMinutes(minutesToAdd)
            .atZone(now.getZone())
            .toInstant();
    System.out.println(inTenDays);

2018-03-04T21:16:19.187690-08:00[America/Los_Angeles]
2018-03-05T05:16:19.187690Z
2018-03-15T04:16:19.187690Z

(DST) 15 ( 11 ), UTC, .

0

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


All Articles