【问题标题】:SimpledateFormat returning different value for different Android versionSimpledateFormat 为不同的 Android 版本返回不同的值
【发布时间】:2013-10-28 10:37:32
【问题描述】:

我在我的代码中使用了SimpleDateFormat,如下所示。

SimpleDateFormat sdf = new SimpleDateFormat("ZZZZ");

我想将结果显示为GMT-05:00。我在 Android 4.3 中运行我的代码。它返回了与我预期相同的结果。但是,对于 Android 版本 4.0、4.1 和 4.2,上述代码行返回 -05:00 而不是 GMT-05:00(缺少 GMT)。我很困惑。我已经阅读了 Android 的 SimpleDateFormat

谁能给我一些想法?

【问题讨论】:

    标签: android timezone simpledateformat


    【解决方案1】:

    由于文档只显示最新版本,我无法找到在 Android 4.3 之前SimpleDateFormat sdf = new SimpleDateFormat("ZZZZ"); 是否总是返回GMT-05:00

    我能想到的最佳近似值是SimpleDateFormat sdf = new SimpleDateFormat("'GMT'Z", Locale.US);,它将显式添加 GMT,但时间格式没有冒号(例如GMT-0500)。


    编辑:如果您可以确保在 4.1 和 4.2 上,您的代码返回 -05:00,那么我认为您可以添加版本检查器并决定将使用哪个 SimpleDateFormat

    if (Build.VERSION.SDK_INT >= 18) {
        SimpleDateFormat sdf = new SimpleDateFormat("ZZZZ", Locale.US);
    } else {
        SimpleDateFormat sdf = new SimpleDateFormat("'GMT'ZZZZ", Locale.US);
    }
    

    【讨论】:

    • 嗨@antimo,我现在在我的代码中使用相同的逻辑。无论如何感谢您的建议。这很奇怪。 :D
    【解决方案2】:

    您可以在任何时区使用DateFormats 将日期转换为字符串:

    DateFormat df = DateFormat.getTimeInstance();
    df.setTimeZone(TimeZone.getTimeZone("gmt"));
    String gmtTime = df.format(new Date());
    

    【讨论】:

    • 谢谢你的建议@ling.s
    【解决方案3】:

    也检查一下:

        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy");
        dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
        System.out.println(dateFormatGmt.format(new Date()));
    

    【讨论】:

      【解决方案4】:

      我遇到了类似的问题,但对于“ZZZZZ”,我发现一些 SimpleDateFormat 修复仅在 4.3+ 上添加:https://code.google.com/p/android/issues/detail?id=73209

      由于 'ZZZZZ' 和 'ZZZZ' 被一起记录,我假设行为在 4.0、4.1 和 4.2 中符合预期

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-22
        • 1970-01-01
        • 2013-11-01
        • 2021-12-11
        相关资源
        最近更新 更多