4

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"

Tunaki
  • 116,530
  • 39
  • 281
  • 370
JJD
  • 44,755
  • 49
  • 183
  • 309

1 Answers1

2

From SimpleDateFormat Javadoc:

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.

Tunaki
  • 116,530
  • 39
  • 281
  • 370
  • 1
    Why is `java.text.SimpleDateFormat` behaving different in the Android context and in JUnit? – JJD Jan 08 '16 at 22:11
  • @JJD The class `SimpleDateFormat` is just not the same in the Android case. – Tunaki Jan 08 '16 at 22:31
  • 1
    So it is impossible to setup tests when the format pattern is defined in Android code? – JJD Jan 08 '16 at 23:28