如何在Java中的UTC + 0中获取日期? [英] How to get Date in UTC+0 in Java?

查看:194
本文介绍了如何在Java中的UTC + 0中获取日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

返回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。

解决方案

当偏移量为零时,内置格式化程序使用 Z Z Zulu 的缩写,表示 UTC



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

  DateTimeFormatter fmt = new DateTimeFormatterBuilder ()
//日期和时间,使用内置的
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
//附加偏移量,当偏移量为零时设置 -00:00
.appendOffset( + HH:MM, -00:00)
//创建格式化程序
.toFormatter();

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

这将打印:


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







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



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

  DateTimeFormatter fmt = new DateTimeFormatterBuilder ()
//日期和时间,使用内置的
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
//附加偏移量
.appendPattern( xxx)
//创建格式化程序
.toFormatter();

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


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



I am using the following code to get the date in ISO-8601 format. For UTC the value returned does not contain offset.

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

return dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);

For other time formats the response returned looks like:

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

In case of UTC the value returned is:

2016-10-30T17:00:00Z

I want it to be:

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

Note: Do not use UTC-0 as -00:00 is not ISO8601 compliant.

解决方案

The built-in formatter uses Z when the offset is zero. The Z is short for Zulu and means UTC.

You'll have to use a custom formatter, using a java.time.format.DateTimeFormatterBuilder to set a custom text for when the offset is zero:

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));

This will print:

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


Just reminding that -00:00 is not ISO8601 compliant. The standard allows only Z and +00:00 (and the variations +0000 and +00) when the offset is zero.

If you want +00:00, just change the code above to:

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

This formatter will produce the output:

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

这篇关于如何在Java中的UTC + 0中获取日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆