How to calculate time difference between two time zones in Java
Chapter:
Date and Time
Last Updated:
20-09-2023 14:43:52 UTC
Program:
/* ............... START ............... */
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.Duration;
public class TimeZoneDifference {
public static void main(String[] args) {
// Define two time zones
ZoneId zone1 = ZoneId.of("America/New_York"); // Example: New York
ZoneId zone2 = ZoneId.of("Europe/London"); // Example: London
// Get the current time in both time zones
ZonedDateTime currentTimeZone1 = ZonedDateTime.now(zone1);
ZonedDateTime currentTimeZone2 = ZonedDateTime.now(zone2);
// Calculate the time difference
Duration timeDifference = Duration.between(currentTimeZone1, currentTimeZone2);
// Print the time difference
System.out.println("Time difference between " + zone1 + " and " + zone2 + " is " +
timeDifference.toHours() + " hours");
}
}
/* ............... END ............... */
Output
Time difference between America/New_York and Europe/London is 5 hours
Notes:
-
First We import the necessary classes from the java.time package.
- Then We define two ZoneId objects, representing the time zones you want to compare (in this case, New York and London).
- Next step get the current time in both time zones using ZonedDateTime.now().
- Then we calculate the time difference between the two ZonedDateTime objects using Duration.between().
- Finally, we print out the time difference in hours using timeDifference.toHours().
- Make sure to replace "America/New_York" and "Europe/London" with the desired time zones for your specific use case.
Tags
How to calculate time difference between two time zones in Java #Java Program to get the difference between two time zones