【问题标题】:"Fri, 12 Sep 2014 05:00:23 GMT",what's wrong with SimpleDateFormat?"Fri, 12 Sep 2014 05:00:23 GMT",SimpleDateFormat 有什么问题?
【发布时间】:2014-11-06 05:00:23
【问题描述】:

“Fri, 12 Sep 2014 05:00:23 GMT”,SimpleDateFormat 有什么问题?

SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.parse(dateString);
format:    "EEE, dd MMM yyyy HH:mm:ss 'GMT'"
dateString:"Fri, 12 Sep 2014 05:00:23 GMT"

怎么了?

【问题讨论】:

  • 错误/预期的输入和输出是什么?
  • 报告错误:java.text.ParseException: Unparseable date: "Fri, 12 Sep 2014 05:00:23 GMT"

标签: android datetime time timezone simpledateformat


【解决方案1】:

假设您的问题是日期出现错误,则时区的 SimpleDateFormat 转换说明符是 z 而不是 'GMT'(尽管您可以将 ZX 用于其他两个变体,分别为 RFC822 和 ISO8601)。

使用您的说明符,我得到一个当地时间早上 5 点的时间。如果我在代码中使用正确的说明符,它可以正常工作:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
    public static void main (String[] args) {
        String format = "EEE, dd MMM yyyy HH:mm:ss z";
        String date = "Fri, 12 Sep 2014 05:00:23 GMT";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            Date dt = sdf.parse(date);
            System.out.println(dt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

该程序的输出(对于西澳大利亚的珀斯,UTC+8)如预期的那样:

Fri Sep 12 13:00:23 WST 2014

更多详情请参阅SimpleDateFormat online documentation

如果您仍然遇到问题,请尝试从格式和日期字符串中删除各个项目,直到它开始工作。一旦确定了有问题的格式说明符,就会更容易追踪。

【讨论】:

  • 为什么我的程序还是有问题?它报告:java.text.ParseException: Unparseable date: "Fri, 12 Sep 2014 05:00:23 GMT"
  • 那么您可能遇到类似语言环境的问题。我假设您已将其更改为使用正确的说明符,是吗?我会用一些建议来更新答案。
【解决方案2】:

在您的模式中使用“z”,因为 GMT 不仅是文字,而且必须被解释为时区偏移 UTC+00:00。并将语言环境设置为英语,因为您有星期几和月份的英文缩写:

String format = "EEE, dd MMM yyyy HH:mm:ss z";
String date = "Fri, 12 Sep 2014 05:00:23 GMT";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多