gpt4 book ai didi

java - JUnit4 测试导致 java.text.ParseException : Unparseable date

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:04 24 4
gpt4 key购买 nike

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

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

现在我将相同的代码 fragment 放入 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 Java文档:

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

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

关于java - JUnit4 测试导致 java.text.ParseException : Unparseable date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34686477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com