fork download
  1. import java.time.LocalDate;
  2. import java.time.LocalDateTime;
  3. import java.time.LocalTime;
  4. import java.time.ZoneId;
  5. import java.time.ZonedDateTime;
  6.  
  7. /*
  8.  * Change the JVM's ZoneId, ZoneId.systemDefault() to the required ZoneId e.g. ZoneId.of("America/New_York")
  9.  */
  10. public class Main {
  11. public static void main(String[] args) {
  12. // Test
  13. ZoneId zoneId = ZoneId.of("Etc/UTC");
  14. ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2021, 5, 10), LocalTime.of(15, 20), zoneId);
  15. System.out.println(zdt + " is " + convertFromZdtToLdt(zdt) + " at " + ZoneId.systemDefault().getId());
  16.  
  17. LocalDateTime ldt = LocalDateTime.of(LocalDate.of(2021, 5, 10), LocalTime.of(15, 20));
  18. System.out
  19. .println(ldt + " at " + ZoneId.systemDefault().getId() + " is " + convertFromLdtZdtToZdt(ldt, zoneId));
  20. }
  21.  
  22. public static LocalDateTime convertFromZdtToLdt(ZonedDateTime zdt) {
  23. return zdt.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
  24. }
  25.  
  26. public static ZonedDateTime convertFromLdtZdtToZdt(LocalDateTime ldt, ZoneId targetZoneId) {
  27. return ldt.atZone(ZoneId.systemDefault()).withZoneSameInstant(targetZoneId);
  28. }
  29. }
Success #stdin #stdout 0.18s 55740KB
stdin
Standard input is empty
stdout
2021-05-10T15:20Z[Etc/UTC] is 2021-05-10T15:20 at GMT
2021-05-10T15:20 at GMT is 2021-05-10T15:20Z[Etc/UTC]