Java:getTimeZone而不返回默认值 [英] Java: getTimeZone without returning a default value
问题描述
我有以下说明:
TimeZone zone = TimeZone.getTimeZone("Asia/Toyo");
很显然,它应该返回null,但是它将返回默认的timeZone,这不是我的情况所希望的行为.从Java Doc:
Obviously, it should return null, but it will return the default timeZone, which is not the desired behaviour for my case. From Java Doc:
返回指定的
TimeZone
,如果无法理解给定的ID,则返回GMT区域.
Returns the specified
TimeZone
, or the GMT zone if the given ID cannot be understood.
如果String不能表示有效的TimeZone,是否可以获取相应的TimeZone和null值?
Is there a way to get corresponding TimeZone and null value if the String does not indicate a valid TimeZone?
我找不到一个好的解决方案来获取所有TimeZones并对其进行迭代.
I don't find a good solution to get all TimeZones and iterate over them.
推荐答案
java.time.ZoneId
现在,旧的日期时间类已被遗留,由java.time类取代.
java.time.ZoneId
The old date-time classes are now legacy, supplanted by the java.time classes.
您应该使用正确的时区名称,请调用
Instead of java.util.TimeZone
, you should be using ZoneId
. For parsing a proper time zone name, call ZoneId.of
.
ZoneId.of ( "Africa/Casablanca" )
诱捕 ZoneRulesException
如果无法识别您传入的名称,则该方法将引发 ZoneRulesException
.
因此,请拼写错误的 亚洲/东京
作为 Asia/Toyo
,捕获 ZoneRulesException
.
So, to catch a misspelling of Asia/Tokyo
as Asia/Toyo
, trap for the ZoneRulesException
.
ZoneId z;
try {
z = ZoneId.of ( "Asia/Toyo" ); // Misspell "Asia/Tokyo" as "Asia/Toyo".
} catch ( ZoneRulesException e ) {
System.out.println ( "Oops! Failed to recognize your time zone name. ZoneRulesException message: " + e.getMessage () );
return;
}
ZonedDateTime zdt = ZonedDateTime.now ( z );
请参见此在IdeOne.com上实时运行的代码.
java.time 框架已内置在Java 8及更高版本中.这些类取代了麻烦的旧版日期时间类,例如 Calendar
,& SimpleDateFormat
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
Joda-Time 项目,现在位于 java.time 类.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
要了解更多信息,请参见 Oracle教程.并在Stack Overflow中搜索许多示例和说明.规范为 JSR 310 .
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
在哪里获取java.time类?
Where to obtain the java.time classes?
- Java SE 8 和 SE 9 及更高版本
- 内置.
- 具有捆绑的实现的标准Java API的一部分.
- Java 9添加了一些次要功能和修复.
- 许多java.time功能都向后移植到Java 6&中.7在> ThreeTen-Backport 中./li>
- > ThreeTenABP 项目适应了<专门用于Android的em> ThreeTen-Backport (上面提到).
- 请参阅 如何使用ThreeTenABP… .
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to use ThreeTenABP….
ThreeTen-Extra 项目使用其他类扩展了java.time.该项目为将来可能在java.time中添加内容提供了一个试验场.您可能会在这里找到一些有用的类,例如
间隔
,年周"
,YearQuarter
和更多The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.这篇关于Java:getTimeZone而不返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!