Java 中的时区验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13092865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TimeZone validation in Java
提问by user1772643
I have a string, I need to check whether it is a standard time zone identifier or not. I am not sure which method I need to use.
我有一个字符串,我需要检查它是否是标准时区标识符。我不确定我需要使用哪种方法。
String timeZoneToCheck = "UTC";
I would like to check whether it represents a valid time zone or not.
我想检查它是否代表有效的时区。
回答by Maciej Dzikowicki
You can write it in one line
你可以写在一行
public boolean validTimeZone(String timezone) {
return Set.of(TimeZone.getAvailableIDs()).contains(timezone);
}
Alternatively, you can make a static field for it
或者,您可以为它创建一个静态字段
private static final Set<String> TIMEZONES = Set.of(TimeZone.getAvailableIDs())
public boolean validTimeZone(String timezone) {
return TIMEZONES.contains(timezone);
}
回答by kosa
You can get all supported ID using getAvailableIDs()
您可以使用getAvailableIDs()获取所有支持的 ID
Then loop the supportedID array and compare with your String.
然后循环 supportedID 数组并与您的字符串进行比较。
Example:
例子:
String[] validIDs = TimeZone.getAvailableIDs();
for (String str : validIDs) {
if (str != null && str.equals("yourString")) {
System.out.println("Valid ID");
}
}
回答by yali
it's simple just use ZoneId.of("Asia/Kolkata")
这很简单,只需使用 ZoneId.of("Asia/Kolkata")
try {
ZoneId.of("Asia/Kolkataa");
} catch (Exception e) {
e.printStackTrace();
}
if your insert invalid time zone it will throw exception
如果您插入无效时区,它将抛出异常
**java.time.zone.ZoneRulesException: Unknown time-zone ID: Asia/Kolkataa**
回答by nvolynets
I would like to propose the next workaround:
我想提出下一个解决方法:
public static final String GMT_ID = "GMT";
public static TimeZone getTimeZone(String ID) {
if (null == ID) {
return null;
}
TimeZone tz = TimeZone.getTimeZone(ID);
// not nullable value - look at implementation of TimeZone.getTimeZone
String tzID = tz.getID();
// check if not fallback result
return GMT_ID.equals(tzID) && !tzID.equals(ID) ? null : tz;
}
As result in case of invalid timezone ID or invalid just custom timezone you will receive null. Additionally you can introduce corresponding nullvalue handler (use case dependent) - throw exception & etc.
因此,如果时区 ID 无效或仅自定义时区无效,您将收到null。此外,您可以引入相应的空值处理程序(取决于用例) - 抛出异常等。
回答by jejare
private boolean isValidTimeZone(final String timeZone) {
final String DEFAULT_GMT_TIMEZONE = "GMT";
if (timeZone.equals(DEFAULT_GMT_TIMEZONE)) {
return true;
} else {
// if custom time zone is invalid,
// time zone id returned is always "GMT" by default
String id = TimeZone.getTimeZone(timeZone).getID();
if (!id.equals(DEFAULT_GMT_TIMEZONE)) {
return true;
}
}
return false;
}
The method returns true for the following:
对于以下情况,该方法返回 true:
assertTrue(this.isValidTimeZone("JST"));
assertTrue(this.isValidTimeZone("UTC"));
assertTrue(this.isValidTimeZone("GMT"));
// GMT+00:00
assertTrue(this.isValidTimeZone("GMT+0"));
// GMT-00:00
assertTrue(this.isValidTimeZone("GMT-0"));
// GMT+09:00
assertTrue(this.isValidTimeZone("GMT+9:00"));
// GMT+10:30
assertTrue(this.isValidTimeZone("GMT+10:30"));
// GMT-04:00
assertTrue(this.isValidTimeZone("GMT-0400"));
// GMT+08:00
assertTrue(this.isValidTimeZone("GMT+8"));
// GMT-13:00
assertTrue(this.isValidTimeZone("GMT-13"));
// GMT-13:59
assertTrue(this.isValidTimeZone("GMT+13:59"));
// NOTE: valid time zone IDs (see TimeZone.getAvailableIDs())
// GMT-08:00
assertTrue(this.isValidTimeZone("America/Los_Angeles"));
// GMT+09:00
assertTrue(this.isValidTimeZone("Japan"));
// GMT+01:00
assertTrue(this.isValidTimeZone("Europe/Berlin"));
// GMT+04:00
assertTrue(this.isValidTimeZone("Europe/Moscow"));
// GMT+08:00
assertTrue(this.isValidTimeZone("Asia/Singapore"));
...And false with the following timezones:
......以下时区为假:
assertFalse(this.isValidTimeZone("JPY"));
assertFalse(this.isValidTimeZone("USD"));
assertFalse(this.isValidTimeZone("UTC+8"));
assertFalse(this.isValidTimeZone("UTC+09:00"));
assertFalse(this.isValidTimeZone("+09:00"));
assertFalse(this.isValidTimeZone("-08:00"));
assertFalse(this.isValidTimeZone("-1"));
assertFalse(this.isValidTimeZone("GMT+10:-30"));
// hours is 0-23 only
assertFalse(this.isValidTimeZone("GMT+24:00"));
// minutes 00-59 only
assertFalse(this.isValidTimeZone("GMT+13:60"));
回答by Minding
This is a more efficient solution, than looping through all possible IDs. It checks the output of getTimeZone
.
这是一个更有效的解决方案,而不是遍历所有可能的 ID。它检查 的输出getTimeZone
。
Java Docs (TimeZone#getTimeZone):
Java 文档 (TimeZone#getTimeZone):
Returns: the specified TimeZone, or the GMTzone if the given ID cannot be understood.
返回: 指定的 TimeZone,如果无法理解给定的 ID,则返回GMT区域。
So if the output is the GMT timezone the input is invalid, except if the input accually was "GMT".
因此,如果输出是 GMT 时区,则输入无效,除非输入实际是“GMT”。
public static boolean isValidTimeZone(@NonNull String timeZoneID) {
return (timeZoneID.equals("GMT") || !TimeZone.getTimeZone(timeZoneID).getID().equals("GMT"));
}
Or if you want to use the valid timezone without calling getTimeZone twice:
或者,如果您想使用有效时区而不调用 getTimeZone 两次:
TimeZone timeZone = TimeZone.getTimeZone(timeZoneToCheck);
if(input.equals("GMT") || !timeZone.getID().equals("GMT")) {
//TODO Valid - use timeZone
} else {
//TODO Invalid - handle the invalid input
}
回答by CoatedMoose
Since TimeZone#getTimeZone(String id)
returns a default if the value is invalid (rather than returning an invalid time zone), if the reinterpreted value does not match the initial value, it wasn't valid.
由于TimeZone#getTimeZone(String id)
如果值无效(而不是返回无效时区),则返回默认值,因此如果重新解释的值与初始值不匹配,则它无效。
private static boolean isValidTimeZone(@Nonnull String potentialTimeZone)
{
// If the input matches the re-interpreted value, then the time zone is valid.
return TimeZone.getTimeZone(potentialTimeZone).getID().equals(potentialTimeZone);
}
回答by Tomasz Nurkiewicz
If TimeZone.getAvailableIDs()
contains ID in question, it's valid:
如果TimeZone.getAvailableIDs()
包含有问题的 ID,则它是有效的:
public boolean validTimeZone(String id) {
for (String tzId : TimeZone.getAvailableIDs()) {
if(tzId.equals(id))
return true;
}
return false;
}
Unfortunately TimeZone.getTimeZone()
method silently discards invalid IDs and returns GMT instead:
不幸的是,该TimeZone.getTimeZone()
方法会默默地丢弃无效 ID 并返回 GMT:
Returns:
the specified TimeZone, or the GMT zone if the given ID cannot be understood.
返回:
指定的时区,如果无法理解给定的 ID,则为 GMT 时区。
回答by Amit Deshpande
You can use TimeZone.getAvailableIDs()
to get list of supported Id
您可以使用TimeZone.getAvailableIDs()
获取支持的 ID 列表
for (String str : TimeZone.getAvailableIDs()) {
if(str.equals("UTC")){
//found
}
}