SimpleDateFormat
解析在 JUnit 测试(Robolectric 测试运行程序)中有效,但如果在设备上运行则失败。
@Test
public void testDateParse() throws ParseException {
String datetime = "Wed Sep 03 12:59:27 BST 2014";
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH)
.parse(datetime);
}
当它在设备上失败时,异常显示:
java.text.ParseException: Unparseable date: "Wed Sep 03 12:59:27 BST 2014" (at offset 20)
偏移量 20 是 BST
的 B
,因此它与时区相关。
确实“GMT”
有效:String datetime =“Wed Sep 03 12:59:27 GMT 2014”;
最佳答案
我想这里有趣的问题是为什么它在 Robolectric 上运行正常但在 Android 测试上运行失败。
Robo 在 JVM 上运行,Android 和优秀的 Java 之间的时区解析行为存在差异。
Other than the special cases "UTC" and "GMT" (which are synonymous in this context, both corresponding to UTC), Android does not support the deprecated three-letter time zone IDs used in Java 1.1.
the ID for a TimeZone, either an abbreviation such as "PST", a full name such as "America/Los_Angeles", or a custom ID such as "GMT-8:00". Note that the support of abbreviations is for JDK 1.1.x compatibility only and full names should be used.
所以答案是不应该使用 3 个字母的缩写(因为它们不明确),但是出于兼容性原因可以在 JVM 上使用,但不能在 Android 上使用。
关于android - 英国夏令时间 - SimpleDateFormat 时区不识别 BST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25668741/