【问题标题】:Why this date is not showing in GMT?为什么这个日期没有在 GMT 中显示?
【发布时间】:2015-08-02 19:53:11
【问题描述】:

我可以看到 GMT 时间的“Z”常数表示它是 GMT 时间。但是,当我解析 GMT 字符串时,它仍然在打印当地时间。

代码:

SimpleDateFormat outFormat = new 
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String timeGMT = "2015-05-21T08:42:27.334Z";
try {
    System.out.println("Time GMT>>>>>>"+outFormat.parse(timeGMT));
} catch (ParseException e) {
    e.printStackTrace();
}

输出:

Thu May 21 08:42:27 IST 2015

预期:

Thu May 21 08:42:27 GMT 2015

【问题讨论】:

标签: java jodatime simpledateformat


【解决方案1】:

这里有两个问题。

首先是你使用了错误的格式来解析。您的格式告诉解析器只需将Z 视为文字字符没有意义

这意味着它会将其解析为本地日期,因为它不会将 Z 视为时区标记。如果您希望将 Z 解释为时区,您的格式中应包含 X 而不是 'Z'

    String timeGMT = "2015-05-21T08:42:27.334Z";

    DateFormat f1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    DateFormat f2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");

    Date d1 = f1.parse(timeGMT);
    Date d2 = f2.parse(timeGMT);

    System.out.println(d1);
    System.out.println(d2);

我目前在 GMT+3,这是我从中得到的输出:

2015 年 5 月 21 日星期四 08:42:27 IDT
2015 年 5 月 21 日星期四 11:42:27 IDT

如您所见,d2 提前 3 小时,这意味着它将原始时间解释为 GMT。

您的另一个问题是您以默认格式打印结果日期。默认格式是您当地的时区,所以它会像我一样在当地时区打印它。

要更改这一点,您还必须格式化输出

    DateFormat f3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    f3.setTimeZone(TimeZone.getTimeZone("GMT"));

    System.out.println(f3.format(d2));

这会产生 - 对于前面的示例 - 如下:

2015-05-21 08:42:27 GMT

【讨论】:

  • 一行 - "If you want the Z to be interpreted as time zone, your format should have X instead of 'Z'。 +1。
【解决方案2】:

您输入中的 Z 不是文字常量,而是表示 UTC+00:00(别名“GMT”)。请从最后一个图案符号周围的图案中删除撇号。并使用“X”而不是“Z”作为符号,以便正确地将“Z”解释为偏移 UTC+00:00 的 ISO-8601 标记。

SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2017-04-26
    相关资源
    最近更新 更多