Java Data Type How to - Convert time between timezone








Question

We would like to know how to convert time between timezone.

Answer

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
/*  w ww  .j a  v a  2 s. c o m*/
public class Main {
  public static void main(String[] argv) {
    
    LocalDateTime now = LocalDateTime.now();
    ZonedDateTime zonedDateTime = ZonedDateTime.of(now, TimeZone.NEW_YORK);
    System.out.println("now = " + now);
    System.out.println("Current date and time in a particular timezone : " + zonedDateTime);

    now = LocalDateTime.now(TimeZone.INDIA);
    System.out.println("now in India = " + now);

    zonedDateTime = ZonedDateTime.now();
    System.out.println("zonedDateTime with default(system) timezone = " + zonedDateTime);
    System.out.println("zonedDateTime with India timezone = " + ZonedDateTime.now(TimeZone.INDIA));

    String isoFormatted = DateTimeFormatter.ISO_INSTANT.format(ZonedDateTime.now(TimeZone.INDIA));
    System.out.println("ISO Formatted = " + isoFormatted);

    ZonedDateTime utahMarch8thAt2AM = ZonedDateTime.of(LocalDateTime.of(2015, 3, 8, 1, 0), TimeZone.UTAH);
    System.out.println("utahMarch8thAt2AM = " + utahMarch8thAt2AM);
    System.out.println("utahMarch8thAt2AM.plusHours(1) = " + utahMarch8thAt2AM.plusHours(1));
    System.out.println("utahMarch8thAt2AM.plusHours(2) = " + utahMarch8thAt2AM.plusHours(2));
  }
}
class TimeZone {
  public static final ZoneId INDIA = ZoneId.of("Asia/Kolkata");
  public static final ZoneId UTAH = ZoneId.of("America/Denver");
  public static final ZoneId NEW_YORK = ZoneId.of("America/New_York");


}

The code above generates the following result.