Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OffsetDateTime - print offset instead of Z

I have this code:

String date = "2019-04-22T00:00:00+02:00";

OffsetDateTime odt = OffsetDateTime
      .parse(date, DateTimeFormatter.ISO_OFFSET_DATE_TIME)                             
      .withOffsetSameInstant(ZoneOffset.of("+00:00"));

System.out.println(odt);

This print: 2019-04-21T22:00Z

How can I print 2019-04-21T22:00+00:00? With offset instead of Z.

like image 761
KunLun Avatar asked Dec 20 '19 17:12

KunLun


1 Answers

None of the static DateTimeFormatters do this in the standard library. They either default to Z or GMT.

To achieve +00:00 for no offset, you will have to build your own DateTimeFormatter.

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
        .append(ISO_LOCAL_DATE_TIME) // use the existing formatter for date time
        .appendOffset("+HH:MM", "+00:00") // set 'noOffsetText' to desired '+00:00'
        .toFormatter();

System.out.println(now.format(dateTimeFormatter)); // 2019-12-20T17:58:06.847274+00:00
like image 151
Cameron Downer Avatar answered Sep 22 '22 00:09

Cameron Downer