Close

Java Date Time - OffsetDateTime.atZoneSameInstant() Examples

Java Date Time Java Java API 


Class:

java.time.OffsetDateTime

java.lang.Objectjava.lang.Objectjava.time.OffsetDateTimejava.time.OffsetDateTimejava.time.temporal.TemporalTemporaljava.time.temporal.TemporalAdjusterTemporalAdjusterjava.lang.ComparableComparablejava.io.SerializableSerializableLogicBig

Method:

public ZonedDateTime atZoneSameInstant(ZoneId zone)

Combines this date-time with a time-zone to create a new instance of ZonedDateTime, adjusting date/time to ensure that the result has the same 'instant'.

This conversion uses underlying 'instant' for desire conversion instead of local date/time fields.



Examples


package com.logicbig.example.offsetdatetime;

import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class AtZoneSameInstantExample {

public static void main (String... args) {
OffsetDateTime d = OffsetDateTime.of(2016, 10, 20,
11, 12, 30, 1000,
ZoneOffset.ofHours(-6));
ZonedDateTime z = d.atZoneSameInstant(ZoneId.of("Asia/Seoul"));
System.out.println(z);
}
}

Output

2016-10-21T02:12:30.000001+09:00[Asia/Seoul]




This example demonstrates that atZoneSameInstant adjusts the DST (Daylight saving time) differences to the resultant target ZoneId.

Offset -5 represents USA central region (CST) during DST and offset -6 also represents the same region but outside of DST. Notice the resultant Offset of Asia/Seoul adjusted by one hour. Before DST the gap between the two was 14 hours and after DST it became 15 hours.

package com.logicbig.example.offsetdatetime;

import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class AtZoneSameInstantExample2 {

public static void main (String... args) {
OffsetDateTime d = OffsetDateTime.of(2016, 11, 6,
0, 20, 30, 1000,
ZoneOffset.ofHours(-5));

System.out.printf("Original OffSetDateTime in DST: %s%n", d);

ZonedDateTime z = d.atZoneSameInstant(ZoneId.of("Asia/Seoul"));
System.out.printf("atZoneSameInstant: %s%n", z);

d = OffsetDateTime.of(2016, 11, 6,
4, 20, 30, 1000,
ZoneOffset.ofHours(-6));

System.out.printf("Original OffSetDateTime after DST: %s%n", d);

z = d.atZoneSameInstant(ZoneId.of("Asia/Seoul"));
System.out.printf("atZoneSameInstant: %s%n", z);

}
}

Output

Original OffSetDateTime in DST: 2016-11-06T00:20:30.000001-05:00
atZoneSameInstant: 2016-11-06T14:20:30.000001+09:00[Asia/Seoul]
Original OffSetDateTime after DST: 2016-11-06T04:20:30.000001-06:00
atZoneSameInstant: 2016-11-06T19:20:30.000001+09:00[Asia/Seoul]




See Also