2

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.

Priya Jain
  • 795
  • 5
  • 15

2 Answers2

2

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

1

If you can accept +00:00 instead of -00:00, you can also use a simpler 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));

I used x whereas the standard toString() method of OffsetDateTime uses X. The main difference between x and X is that one return +00:00 vs. Z for the other.

assylias
  • 321,522
  • 82
  • 660
  • 783