Android Studio Convert ISO string to "America/New_York" when adding to event to calendar
Solution 1:
That is because you're telling the parser to ignore the Z
, or rather to match it literally, but not to process it's meaning.
The input strings are Instant
values, so parse to Instant
, then apply time zone.
If you don't have Java 8+ compatible Android, use ThreeTenABP.
String stTime = "2018-10-17T22:00:00Z";
ZonedDateTime time = Instant.parse(stTime).atZone(ZoneId.of("America/New_York"));
System.out.println(time); // prints: 2018-10-17T18:00-04:00[America/New_York]
If you prefer using antiquated SimpleDateFormat
, simply use the correct format, and don't specify time zone.
SimpleDateFormat formatStart = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date startDate = formatStart.parse(stTime);
// My default time zone is America/New_York, so:
System.out.println(startDate); // prints: Wed Oct 17 18:00:00 EDT 2018
startDate.getTime()
is the time-in-millis you need.
For API Level < 24, format pattern X
doesn't work, so you need to do the hardcoded Z
like in your question, but tell the parser that it is in UTC, because that is what the Z
time zone means.
SimpleDateFormat formatStart = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
formatStart.setTimeZone(TimeZone.getTimeZone("UTC"));
Date startDate = formatStart.parse(stTime);
// My default time zone is America/New_York, so:
System.out.println(startDate); // prints: Wed Oct 17 18:00:00 EDT 2018