Priya Jain Priya Jain - 2 years ago 109
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

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 offset, set "-00:00" when offset is zero
    .appendOffset("+HH:MM", "-00:00")
    // create formatter


This will print:


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