Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

timezone - Java: getTimeZone without returning a default value

I have the following instruction:

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

Obviously, it should return null, but it will return the default timeZone, which is not the desired behaviour for my case. From Java Doc:

Returns the specified TimeZone, or the GMT zone if the given ID cannot be understood.

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

I don't find a good solution to get all TimeZones and iterate over them.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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" ) 

Trap for ZoneRulesException

If the name you pass in unrecognized, the method throws a 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 );

See this code run live at IdeOne.com.


About java.time

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.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...