Java Date Time - ZoneId Example








Example

The following code shows how to Compare the same time in different time zone.

import java.time.LocalTime;
import java.time.ZoneId;
/*from  www.  j  a v a 2  s .  com*/
public class Main {
  public static void main(String... args) {
    ZoneId zone1 = ZoneId.of("Europe/Berlin");
    ZoneId zone2 = ZoneId.of("Brazil/East");

    LocalTime now1 = LocalTime.now(zone1);
    LocalTime now2 = LocalTime.now(zone2);

    System.out.println(now1);
    System.out.println(now2);

    System.out.println(now1.isBefore(now2));  // false

  }
}

The code above generates the following result.





Example 2

The following code shows how to convert current date and time to another time zone.

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
//from   w ww.j a v a 2s .c  om
public class Main {
  public static void main(String[] args) {
    Set<String> allZones = ZoneId.getAvailableZoneIds();
    List<String> zoneList = new ArrayList<String>(allZones);
    Collections.sort(zoneList);

    LocalDateTime dt = LocalDateTime.now();
    for (String s : zoneList) {
      ZoneId zone = ZoneId.of(s);
      ZonedDateTime zdt = dt.atZone(zone);
      ZoneOffset offset = zdt.getOffset();
      String out = String.format("%35s %10s%n", zone, offset);
      System.out.println(out);
    }
  }
}

The code above generates the following result.





Example 3

The following code shows how to Get local time for different time zone.

import java.time.LocalTime;
import java.time.ZoneId;
/*  w  w  w.  jav a 2  s. c  om*/
public class Main {
  public static void main(String... args) {
    ZoneId zone1 = ZoneId.of("Europe/Berlin");
    ZoneId zone2 = ZoneId.of("Brazil/East");

    LocalTime now1 = LocalTime.now(zone1);
    LocalTime now2 = LocalTime.now(zone2);

    System.out.println(now1);
    System.out.println(now2);



  }
}

The code above generates the following result.

Field

  1. ZoneId SHORT_IDS

Method

  1. ZoneId equals(Object obj)
  2. ZoneId from(TemporalAccessor temporal)
  3. ZoneId getAvailableZoneIds()
  4. ZoneId getDisplayName(TextStyle style, Locale locale)
  5. ZoneId getId()
  6. ZoneId getRules()
  7. ZoneId hashCode()
  8. ZoneId normalized()
  9. ZoneId ofOffset(String prefix, ZoneOffset offset)
  10. ZoneId of(String zoneId)
  11. ZoneId of(String zoneId, Map aliasMap)
  12. ZoneId systemDefault()
  13. ZoneId toString()