Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

As an input I have a string which is a String in ISO 8601 to represent date. For example:

"2017-04-04T09:00:00-08:00"

The last part of String, which is "-08:00" denotes TimeZone Offset. I convert this string into a Calendar instance as shown below:

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 pick timezone and if I get timezone from Calendar instance, it gives currently set instance of the laptop and does not pick up timestamp from ISO 8601 String. I check for timezone via calendar instance as:

calendar.getTimeZone().getDisplayName()

Can someone show how to pick timezone also in the Calendar instance?

like image 843
Tarun Deep Attri Avatar asked Mar 08 '23 03:03

Tarun Deep Attri


1 Answers

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?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use ThreeTenABP….
like image 179
Basil Bourque Avatar answered Apr 05 '23 22:04

Basil Bourque