java.time
: the modern date-time API
You can get the offset of a timezone using ZonedDateTime#getOffset
.
Note that the offset of a timezone that observes DST changes as per the changes in DST. For other places (e.g. India), it remains fixed. Therefore, it is recommended to mention the moment when the offset of a timezone is shown. A moment is mentioned as Instant.now()
and it represents the date-time in UTC (represented by Z
which stands for Zulu and specifies the timezone offset of +00:00
hours).
Display offset of all timezones returned by ZoneId.getAvailableZoneIds()
:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// Test
Instant instant = Instant.now();
System.out.println("Timezone offset at " + instant);
System.out.println("==============================================");
ZoneId.getAvailableZoneIds()
.stream()
.sorted()
.forEach(strZoneId -> System.out.printf("%-35s: %-6s%n",
strZoneId, getTzOffsetString(ZoneId.of(strZoneId), instant)));
}
static String getTzOffsetString(ZoneId zoneId, Instant instant) {
return ZonedDateTime.ofInstant(instant, zoneId).getOffset().toString();
}
}
Output:
Timezone offset at 2021-05-05T21:45:34.150901Z
==============================================
Africa/Abidjan : Z
Africa/Accra : Z
Africa/Addis_Ababa : +03:00
...
...
...
W-SU : +03:00
WET : +01:00
Zulu : Z
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.