Java Data Type How to - Change Instant to various timezone








Question

We would like to know how to change Instant to various timezone.

Answer

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
//  w w  w .j av  a  2  s  . c om
public class Main {

  public static void main(String[] args) {
    Clock utcClock = Clock.systemUTC();
    Clock defaultClock = Clock.systemDefaultZone();
    Clock offsetClock = Clock.offset(Clock.systemUTC(), Duration.ofHours(-5));

    ZoneId denverTimeZone = ZoneId.of("America/Denver");
    ZoneId newYorkTimeZone = ZoneId.of("America/New_York");
    ZoneId chicagoTimeZone = ZoneId.of("America/Chicago");
    ZoneId losAngelesTimeZone = ZoneId.of("America/Los_Angeles");

    Instant instant = Instant.now(defaultClock);
    Instant instant2 = Instant.now(utcClock);
    Instant instant3 = Instant.now(offsetClock);

    System.out.println(instant);
    System.out.println(instant2);
    System.out.println(instant3.plus(Duration.ofSeconds(90)));
    System.out.println(instant3.atZone(newYorkTimeZone));
    System.out.println(instant3.atZone(chicagoTimeZone));
    System.out.println(instant3.atZone(denverTimeZone));
    System.out.println(instant3.atZone(losAngelesTimeZone));
  }
}

The code above generates the following result.