【问题标题】:How to get Date in UTC+0 in Java? [duplicate]如何在 Java 中获取 UTC+0 的日期? [复制]
【发布时间】:2017-07-27 11:56:06
【问题描述】:

我正在使用以下代码来获取 ISO-8601 格式的日期。对于 UTC,返回的值不包含偏移量。

OffsetDateTime dateTime = OffsetDateTime.ofInstant(
                                       Instant.ofEpochMilli(epochInMilliSec), zoneId);

return dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);

对于其他时间格式,返回的响应如下所示:

2016-10-30T17:00:00-07:00

如果是 UTC,则返回的值为:

2016-10-30T17:00:00Z

我希望它是:

2016-10-30T17:00:00+00:00

注意:不要使用 UTC-0,因为 -00:00 不符合 ISO8601。

【问题讨论】:

标签: java datetime datetime-format java-time


【解决方案1】:

当偏移量为零时,内置格式化程序使用ZZZulu 的缩写,意思是 UTC

您必须使用自定义格式化程序,使用 java.time.format.DateTimeFormatterBuilder 设置偏移量为零时的自定义文本:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    // date and time, use built-in
    .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
    // append offset, set "-00:00" when offset is zero
    .appendOffset("+HH:MM", "-00:00")
    // create formatter
    .toFormatter();

System.out.println(dateTime.format(fmt));

这将打印:

2016-10-30T17:00:00-00:00


只是提醒-00:00 不是ISO8601 compliant。当偏移量为零时,该标准仅允许Z+00:00(以及+0000+00 的变体)。

如果你想要+00:00,只需将上面的代码更改为:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    // date and time, use built-in
    .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
    // append offset
    .appendPattern("xxx")
    // create formatter
    .toFormatter();

此格式化程序将产生输出:

2016-10-30T17:00:00+00:00

【讨论】:

  • 不是在所有情况下都附加 -00:00 吗?
  • 我的错..不会
  • @PriyaJain 只有当偏移量为零时它才会附加-00:00。对于所有其他偏移量,它将遵循格式 +HH:MM(信号 + 或 - 后跟小时:分钟)
  • @Hugo 哦,我没看到-,很公平。
  • @PriyaJain 只是提醒 -00:00 不符合 ISO8601:en.wikipedia.org/wiki/ISO_8601#Time_zone_designators - 当偏移量为零时,标准只允许 Z+00:00
【解决方案2】:

如果你可以接受+00:00而不是-00:00,你也可以使用更简单的DateTimeFormatter

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssxxx");

OffsetDateTime odt = OffsetDateTime.parse("2016-10-30T17:00:00Z");
System.out.println(fmt.format(odt));

我使用了x,而OffsetDateTime 的标准toString() 方法使用XxX 之间的主要区别在于,一个返回 +00:00 而另一个返回 Z

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 2013-07-23
    • 2021-04-13
    • 2017-05-28
    • 2011-10-17
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    相关资源
    最近更新 更多