android - 英国夏令时间 - SimpleDateFormat 时区不识别 BST

标签 android

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 是 BSTB,因此它与时区相关。

确实“GMT”有效:String datetime =“Wed Sep 03 12:59:27 GMT 2014”;

最佳答案

我想这里有趣的问题是为什么它在 Robolectric 上运行正常但在 Android 测试上运行失败。

Robo 在 JVM 上运行,Android 和优秀的 Java 之间的时区解析行为存在差异。

Android documentation :

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.

Java documentation :

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/

相关文章:

android - 在我设置了 Locale.setDefault(locale) 之后,我怎样才能取回电话语言?

java - 在 Android 中从没有像素透明度的 Drawable 创建形状

应用程序被杀死时Android后台服务正在重新启动

android - TextView Html格式

android - 错误异步任务 doInBackground() & JSoup

android - 如何在编辑模式下扩充布局?

android - margin 仍然存在于替换的 fragment 中

java - 如何安装 assets 文件夹大小 > 1GB 而 apk 最大大小 = 50 MB 的 android 应用程序?

Android 无法 POST/api 响应

android - SQlite 查询在 2 列中搜索字符串