java.time
The question and the answer written at that time use the java.util
date-time API which was the right thing to do in 2011. In March 2014, the modern Date-Time API was released as part of the Java 8 standard library which supplanted the legacy date-time API and since then it is strongly recommended to switch to java.time
, the modern date-time API.
Solution using java.time
Do not use three-letter timezone ID: Before doing it using the modern date-time API, let's see the following important note from the Java 7 Timezone
documentation:
Three-letter time zone IDs
For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are
also supported. However, their use is deprecated because the same
abbreviation is often used for multiple time zones (for example, "CST"
could be U.S. "Central Standard Time" and "China Standard Time"), and
the Java platform can then only recognize one of them.
The desired solution:
import java.time.Instant;
import java.time.ZoneId;
import java.util.concurrent.TimeUnit;
class Main {
public static void main(String[] args) {
Instant now = Instant.now();
long offest1InSec = ZoneId.of("America/New_York").getRules().getOffset(now).getTotalSeconds();
long offest2InSec = ZoneId.of("Etc/UTC").getRules().getOffset(now).getTotalSeconds();
long hours = TimeUnit.HOURS.convert(offest2InSec - offest1InSec, TimeUnit.SECONDS);
System.out.println(hours);
}
}
Output now*:
5
ONLINE DEMO
It gets even simpler if the desired difference is from GMT/UTC
The above solution is a general solution for any two time zones. However, if the desired difference is from GMT/UTC, it gets even simpler. In this case, you don't need to calculate the difference because the offset of a time zone is always given w.r.t. UTC whose offset is 00:00
hours.
Demo:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.TimeUnit;
class Main {
public static void main(String[] args) {
long hours = Math.abs(TimeUnit.HOURS.convert(
ZoneId.of("America/New_York").getRules().getOffset(Instant.now()).getTotalSeconds(), TimeUnit.SECONDS));
System.out.println(hours);
// Alternatively,
hours = Math.abs(TimeUnit.HOURS.convert(
ZonedDateTime.now(ZoneId.of("America/New_York")).getOffset().getTotalSeconds(), TimeUnit.SECONDS));
System.out.println(hours);
}
}
Output:
5
5
Learn more about the modern Date-Time API from Trail: Date Time.
* US Eastern Time (e.g. America/New_York) observes DST. During the DST period, its offset from UTC is 4 hours and during the non-DST period (e.g. now, 28-Jan-2023), it's 5 hours. Check this page to learn more about it.