Java Program to get the difference between two time zones by seconds

Java 8Object Oriented ProgrammingProgramming

Here are the two timezones −

ZoneId zone1 = ZoneId.of("America/Panama");
ZoneId zone2 = ZoneId.of("Asia/Taipei");

Set the date −

LocalDateTime dateTime = LocalDateTime.of(2019, 04, 11, 10, 5);

Now, set the first timezone −

ZonedDateTime panamaDateTime = ZonedDateTime.of(dateTime, zone1);

Set the second timezone −

ZonedDateTime taipeiDateTime = panamaDateTime.withZoneSameInstant(zone2);

Get the timezone differences in seconds −

taipeiDateTime.getOffset().getTotalSeconds()

Example

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Demo {
   public static void main(String[] args) {
      ZoneId zone1 = ZoneId.of("America/Panama");
      ZoneId zone2 = ZoneId.of("Asia/Taipei");
      LocalDateTime dateTime = LocalDateTime.of(2019, 04, 11, 10, 5);
      ZonedDateTime panamaDateTime = ZonedDateTime.of(dateTime, zone1);
      ZonedDateTime taipeiDateTime = panamaDateTime.withZoneSameInstant(zone2);
      System.out.println("Difference between two time zones in seconds = "+taipeiDateTime.getOffset().getTotalSeconds());
   }
}

Output

Difference between two time zones in seconds = 28800
raja
Published on 26-Apr-2019 06:56:47
Advertisements