withZoneSameInstant Versus withZoneSameLocal
Convert time zones with withZoneSameInstant to keep the same moment, or withZoneSameLocal to keep the wall clock and knowingly change the instant.
Code
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class ZoneConverter {
public static void main(String[] args) {
ZonedDateTime tokyoMeeting = ZonedDateTime.of(
LocalDateTime.of(2026, 11, 19, 14, 0), ZoneId.of("Asia/Tokyo"));
// withZoneSameInstant:同一时刻换时区,墙钟数字随偏移平移
ZonedDateTime utcInstant = tokyoMeeting.withZoneSameInstant(ZoneId.of("UTC"));
System.out.println("sameInstant: " + utcInstant);
// withZoneSameLocal:墙钟数字不变,时刻本身被改写(versus 对照)
ZonedDateTime utcLocal = tokyoMeeting.withZoneSameLocal(ZoneId.of("UTC"));
System.out.println("sameLocal: " + utcLocal);
// 两条转换相差的正是两个时区之间的偏移
long diffHours = Math.abs(Duration.between(
utcInstant.toInstant(), utcLocal.toInstant()).toHours());
System.out.println("instant gap hours: " + diffHours);
}
}What the code does
Under the hood: the class ZoneConverter and the function main.
Caveats
- Copy, run: the standard library answers every call in the file.
Applying it
The run emits 3 labeled sections — sameInstant:, sameLocal:, instant gap hours: — one per step.
Statements that matter
ZonedDateTime utcInstant = tokyoMeeting.withZoneSameInstant(ZoneId.of("UTC"));
ZonedDateTime utcLocal = tokyoMeeting.withZoneSameLocal(ZoneId.of("UTC"));
Interactive Tools for This Topic
Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
FAQ
- What does withZoneSameInstant Versus withZoneSameLocal print when run?
- The script runs standalone; its 3 labeled outputs include `sameInstant:`, `sameLocal:`, `instant gap hours:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.