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?
OffsetDateTime.parse( "2017-04-04T09:00:00-08:00" )
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() ;
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With