I can successfully execute the following code snippet in an Android project:
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = dateFormat.parse("2015-08-17T19:30:00+02:00");
} catch (ParseException e) {
e.printStackTrace();
}
Now I put the same code snippet into a JUnit4 test:
@RunWith(JUnit4.class)
public class DateUtilsTests {
@Test
public void testFailsWithParseException() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = dateFormat.parse("2015-08-17T19:30:00+02:00");
} catch (ParseException e) {
e.printStackTrace();
}
assertThat(date).isNotEqualTo(null);
}
}
This fails:
java.text.ParseException: Unparseable date: "2015-08-17T19:30:00+02:00"
From SimpleDateFormat
Javadoc:
Z
corresponds to RFC 822 time zone (like -0800
)X
corresponds to ISO 8601 time zone (like -08
or -0800
or -08:00
)In your case, you want to parse a timezone written in the form +02:00
(i.e. with a colon between the hours and minutes) so you should use the X
token instead of Z
.
However, in Android, SimpleDateFormat
doesn't have the X
token, only Z
, and the documentation states that Z
supports parsing a timezone of the format -08:00
.
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