Java – How to select a time zone from an ISO 8601 format string into a calendar instance

How to select a time zone from an ISO 8601 format string into a calendar instance… here is a solution to the problem.

How to select a time zone from an ISO 8601 format string into a calendar instance

As input, I have a string, which is a string in ISO 8601 that represents a date. For example:

“2017-04-04T09:00:00-08:00”

The last part of the string, “-08:00”, represents the time zone offset. I converted this string to a Calendar instance as follows:

Calendar calendar = GregorianCalendar.getInstance();
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).parse(iso8601Date);
calendar.setTime(date);

ISO8601Date is “2017-04-04T09:00:00-08:00”

But this does not select the time zone,

if I get the time zone from the Calendar instance, it provides the current settings instance of the laptop and does not get the timestamp from the ISO 8601 string. I check the time zone through the calendar instance as:

calendar.getTimeZone().getDisplayName()

Can someone show how to select a time zone in a Calendar instance?

Solution

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 the offset with the time zone.

-08:00 means offset-from-UTC , no time zone. Time zones are named after continents, slashes, and regions, such as America/Los_Angeles or Pacific/Auckland or Asia/Kolkata

You are using the troublesome old datetime class, now superseded by the java.time class. For Android, see ThreeTen-Backport ThreeTenABP project.

Your input indicates only the offset and not the region. So we resolve it as OffsetDateTime

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

If you are absolutely sure of the expected time zone, assign it.

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

About java.time

placed in Java 8 and later within the java.time framework. These classes replace the troublesome old classes legacy datetime classes, eg java.util.Date , Calendar , & SimpleDateFormat .

Joda-Time project, now in maintenance mode, it is recommended to migrate to java.time class.

To learn more, see Oracle Tutorial. The specification is JSR 310

Where do I get the java.time class?

Related Problems and Solutions