Home > Net >  Java 8 : formatting Instant according to ISO 8601 with Zone-Offset
Java 8 : formatting Instant according to ISO 8601 with Zone-Offset

Time:06-23

I'm trying to create the ISO 8601 formatted DateTime from the Instant object as per the reference in this article I used the format YYYY-MM-DD'T'hh:mm:ss'T'ZD to parse the Instant date as below.

But it's generating the time in wrong format:

2022-06-172T06:08:13T-0500172

The expected format should be:

2022-06-21T13:31:49-05:00

My code:

DateTimeFormatter formatter = DateTimeFormatter
            .ofPattern("YYYY-MM-DD'T'hh:mm:ss'T'ZD")
            .withZone(ZoneId.systemDefault());

formatter.format(Instant.now())

How can I produce the formatted time as shown below?

2022-06-21T13:31:49-05:00

CodePudding user response:

I guess the pattern you need is "yyyy-MM-dd'T'hh:mm:ssxxx"

  • y - year (not Y - week-based-year);
  • d - day of the month (not D - day of the year);
  • x - zone-offset (not ZD);
  • There's no need in T in the end if you don't want it to be present in the formatted string.

Quote from the documentation regarding the zone-offset formatting:

Offset X and x: This formats the offset based on the number of pattern letters. One letter outputs just the hour, such as ' 01', unless the minute is non-zero in which case the minute is also output, such as ' 0130'. Two letters outputs the hour and minute, without a colon, such as ' 0130'. Three letters outputs the hour and minute, with a colon, such as 01:30.

DateTimeFormatter formatter = DateTimeFormatter
    .ofPattern("yyyy-MM-dd'T'hh:mm:ssxxx")
    .withZone(ZoneId.systemDefault());
    
System.out.println(formatter.format(Instant.now()));

Output:

2022-06-22T03:05:43 03:00

CodePudding user response:

tl;dr

help with producing the time formatted as 2022-06-21T13:31:49-05:00

OffsetDateTime.now().toString()

2022-06-22T04:38:55.902569200 03:00

ISO 8601

No need to define a formatting pattern.

Your desired output complies with ISO 8601 standard of date-time formats. The java.time classes use these standard formats by default when parsing/generating text.

OffsetDateTime

To represent a moment as seen in a particular offset, use OffsetDateTime.

OffsetDateTime odt = OffsetDateTime.now() ;

Generate your text by calling toString.

String output = odt.toString() ;

2022-06-22T04:38:55.902569200 03:00

If you want to discard the fractional second, truncate.

OffsetDateTime
.now()
.truncatedTo( ChronoUnit.SECONDS )
.toString()

2022-06-22T04:38:55 03:00

  • Related