本文介绍了Java:getTimeZone 不返回默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下指令:

TimeZone zone = TimeZone.getTimeZone("Asia/Toyo");

显然,它应该返回 null,但它会返回默认时区,这不是我所希望的行为.来自 Java 文档:

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 时区.

如果String不表示有效的TimeZone,有没有办法获取对应的TimeZone和null值?

Is there a way to get corresponding TimeZone and null value if the String does not indicate a valid TimeZone?

我没有找到一个很好的解决方案来获取所有 TimeZone 并对其进行迭代.

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.

您应该使用 .要解析 正确的时区名称,请调用 ZoneId.of.

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/Tokyo 作为 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 及更高版本.这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date, 日历, &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 8SE 9 及更高版本
    • 内置.
    • 标准 Java API 的一部分,带有捆绑实现.
    • Java 9 添加了一些小功能和修复.
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use ThreeTenABP….

    ThreeTen-Extra 项目通过附加类扩展了 java.time.该项目是未来可能添加到 java.time 的试验场.您可以在这里找到一些有用的类,例如 间隔YearWeek, 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 不返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 02:22