Priya Jain Priya Jain - 1 year ago 86
Java Question

How to get Date in UTC-0 in Java?

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.

Answer Source

The built-in formatter uses Z when the offset is zero.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download