How to Pick Timezone from ISO 8601 format String into a Calendar instace

与世无争的帅哥 提交于 2019-12-01 22:09:48

When you create a Calendar, it takes the JVM's default timezone. And when you parse a String to a Date, it just sets one value: the number of milliseconds since epoch (1970-01-01T00:00Z). A Date doesn't have any timezone information, just this milliseconds value. So you need to set the timezone in the calendar.

In your formatter, you're treating Z as a literal, because it's inside quotes ('Z'). This ignores the offset and gets the date in the JVM default timezone (which will have a different value if the corresponding offset is not -08:00).

In JDK >= 7, you can use the X pattern to parse the offset:

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.US).parse(iso8601Date);

But this doesn't set the timezone in the calendar (it will still use the JVM's default). So, a "better" way is to strip the offset from the input and handle it separately:

Calendar calendar = GregorianCalendar.getInstance();
String iso8601Date = "2017-04-04T09:00:00-08:00";
// get the offset (-08:00)
String offset = iso8601Date.substring(19);
TimeZone tz = TimeZone.getTimeZone("GMT" + offset);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
// set the offset in the formatter
sdf.setTimeZone(tz);
// parse just date and time (without the offset)
Date date = sdf.parse(iso8601Date.substring(0, 19));
// set the offset in the calendar
calendar.setTimeZone(tz);
calendar.setTime(date);

With this, the calendar will have the offset -08:00 set. As @BasilBourque's answer already said, -08:00 is an offset, not a timezone (the TimeZone class treats offsets just like they were timezones, which is a workaround/bad design choice).


Java new Date/Time API

The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.

In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. You'll also need the ThreeTenABP to make it work (more on how to use it here).

@BasilBourque's answer already tells you about OffsetDateTime. But to convert to a Calendar, you can use a org.threeten.bp.ZonedDateTime and convert it using the org.threeten.bp.DateTimeUtils class:

String iso8601Date = "2017-04-04T09:00:00-08:00";
ZonedDateTime zdt = ZonedDateTime.parse(iso8601Date);
Calendar cal = DateTimeUtils.toGregorianCalendar(zdt);

The calendar will be already set with the -08:00 offset.


If you want to get the timezone from the offset, I'm afraid it's not that simple. More than one timezone can use the same offset, so you can't know for sure which timezone to use (the best you can do is to get a list of possible candidates).


java.util.Date

Just a more detailed note about java.util.Date. This link explains a lot about it, so I really recommend you to read it.

As already said above, a Date has no timezone information. It just keeps the number of milliseconds since epoch (which is 1970-01-01T00:00Z, or January 1st 1970 at midnight in UTC).

This value is the same everywhere in the world. Example: at the moment I'm writing this, the millis value for the current time is 1504632865935. This number is the same for anyone in the world who gets the current time at the same instant I did, regardless of what timezone they're using.

What is different is the local date and time that corresponds to this millis value. In UTC, it corresponds to 2017-09-05T17:34:25.935Z, in New York, the date is the same (September 5th 2017) but the time is different (13:34), and in Tokyo is September 6th 2017 at 02:34 AM.

Although the Date object is the same (because its millis value is 1504632865935 for everyone), the corresponding date and time changes according to the timezone used.

People tend to think that a Date has a timezone because when printing it (with System.out.println or by loggging) or when inspecting in a debugger, it implicity uses the toString() method, and this converts the date to the JVM's default timezone (and it also prints the zone name). This gives the impression that a Date has a format and a timezone set to it, but it doesn't.

tl;dr

OffsetDateTime.parse( "2017-04-04T09:00:00-08:00" ) 

Details

The last part of String which is "-08:00" denotes TimeZone Offset.

Do not confuse offset with time zone.

The -08:00 represents an offset-from-UTC, not a time zone. A time zone is a history of various offsets used in the past, present, and future by the people of a particular region. A time zone is named with a continent, slash, and region such as America/Los_Angeles or Pacific/Auckland or Asia/Kolkata.

You are using troublesome old date-time classes now supplanted by the java.time classes. For Android, see the ThreeTen-Backport and ThreeTenABP projects.

Your input indicates only offset but not zone. So we parse as a OffsetDateTime.

OffsetDateTime odt = OffsetDateTime.parse( "2017-04-04T09:00:00-08:00" ) ;

If you are absolutely certain of the intended time zone, assign it.

ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant() ;

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?

One Key understanding I want to share from Hugo's answer and my further search is following. Please correct me if I am wrong:

Date does not care about timezone. It represents milliseconds passed since epoch.

Regarding finding the Timezone from provided ISO 8061 format is there, Date class can not tell that and we have to use some alternate methods as specified by @Hugo and @Basil Bourque.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!