Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit4 test causes java.text.ParseException: Unparseable date

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"

like image 468
JJD Avatar asked Oct 18 '22 18:10

JJD


1 Answers

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.

like image 180
Tunaki Avatar answered Oct 21 '22 10:10

Tunaki