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


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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

623 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements