java.time
The legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
Solution using the modern API:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Replace ZoneId as applicable e.g. ZoneId.of("America/New_York")
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("XX", Locale.ENGLISH);
String offset = dtf.format(now);
System.out.println(offset);
}
}
Output:
+0100
Learn more about the the modern date-time API* from Trail: Date Time.
Feedback from Ole V.V.:
You may want to use lower case xx
so you also get +0000
rather than
Z
for offset zero.
Thanks, Ole V.V. for the value addition which will benefit someone looking for +0000
rather than Z
for a zero-timezone offset. I recommend using this strictly based on the specific requirement. ISO 8601 recommends using Z
as the timezone designator for a zero-timezone offset.
* 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.