JUnit4 测试原因 java.text.ParseException:无法解析的日期

JUnit4 test causes java.text.ParseException: Unparseable date

我可以在 Android 项目中成功执行以下代码片段:

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();
}

现在我将相同的代码片段放入 JUnit4 测试中:

@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);
    }

}

这失败了:

java.text.ParseException: Unparseable date: "2015-08-17T19:30:00+02:00"

来自 SimpleDateFormat Javadoc:

在您的情况下,您想要解析以 +02:00 形式编写的时区(即在小时和分钟之间使用冒号),因此您应该使用 X 标记而不是 Z.

但是,在 Android 中,SimpleDateFormat 没有 X 标记,只有 Z,并且文档指出 Z 支持解析-08:00.

格式的时区