java.time
Quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API: Process ZoneId.of
under try/catch
and catch the exception for the invalid timezone ID.
Demo:
import java.time.ZoneId;
import java.time.zone.ZoneRulesException;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Stream.of(
"America/New_York",
"GMT",
"UTC",
"UCT",
"GMT+01:00",
"UTC+01:00",
"ABC"
).forEach(s -> {
try {
System.out.println(ZoneId.of(s));
} catch (ZoneRulesException e) {
System.out.println(e.getMessage());
}
});
}
}
Output:
America/New_York
GMT
UTC
UCT
GMT+01:00
UTC+01:00
Unknown time-zone ID: ABC
ONLINE DEMO
I do not recommend ZoneId.getAvailableZoneIds().contains(time-zone-id)
because it may fail for some cases as shown below:
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Set;
public class Main {
public static void main(String[] args) {
String[] arr = { "America/New_York", "GMT", "UTC", "UCT", "GMT+01:00", "UTC+01:00", "ABC" };
// Alternatively
Set<String> allZones = ZoneId.getAvailableZoneIds();
Arrays.stream(arr).forEach(s -> System.out.println(allZones.contains(s) ? s : ("Unknown time-zone ID: " + s)));
}
}
Output:
America/New_York
GMT
UTC
UCT
Unknown time-zone ID: GMT+01:00
Unknown time-zone ID: UTC+01:00
Unknown time-zone ID: ABC
ONLINE DEMO
Learn more about 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.