如何在Java中获取UTC + 0的日期?

问题描述:

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

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兼容。

+0

http://www.joda。org/joda-time/ – sForSujit

当偏移量为零时,内置格式化程序使用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

+0

在所有情况下都不会附加-00:00吗? –

+0

我的坏..它不会 –

+0

@PriyaJain只有当偏移量为零时它才会附加'-00:00'。对于所有其他偏移量,它将遵循格式'+ HH:MM'(信号+或 - 然后小时:分钟) – 2017-07-27 12:12:42

如果您可以接受+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