How to get date in UTC + 0 in Java?

I use the following code to get the date in ISO-8601 format. For UTC, the return value does not contain an 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 this:

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

In case of UTC, the return value is:

2016-10-30T17: 00: 00Z

I want this to be:

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

Note. Do not use UTC-0, since -00: 00 does not comply with ISO8601.

+2
java datetime java-time datetime-format
Jul 27 '17 at 11:56 on
source share
2 answers

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

You will need to use your own formatter using java.time.format.DateTimeFormatterBuilder to set your own text 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




We remind you that -00:00 not compatible with ISO8601 . The standard allows only Z and +00:00 (and variations +0000 and +00 ) when the offset is zero.

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

 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 result:

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

+2
Jul 27 '17 at 12:05
source share

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 returns +00:00 vs. Z for another.

0
Jul 27 '17 at 12:14
source share



All Articles