3

This code

String formattedDate = OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE);
OffsetDateTime.parse(formattedDate, DateTimeFormatter.ISO_OFFSET_DATE);

leads to

java.time.format.DateTimeParseException: Text '2020-11-27+01:00' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {OffsetSeconds=3600},ISO resolved to 2020-11-27 of type java.time.format.Parsed

Shouldn't this work?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Buka
  • 226
  • 3
  • 12

1 Answers1

3

As the name suggests, OffsetDateTime needs time components (hour, minute etc.) as well. DateTimeFormatter.ISO_OFFSET_DATE does not have pattern for time components and therefore you should not use it to parse a date string into OffsetDateTime. You can build a formatter with default time components.

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String formattedDate = OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE);
        System.out.println(formattedDate);

        DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                .append(DateTimeFormatter.ISO_OFFSET_DATE)
                                .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                                .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                                .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                                .toFormatter(Locale.ENGLISH);

        OffsetDateTime odt = OffsetDateTime.parse(formattedDate, dtf);
        System.out.println(odt);
        System.out.println(DateTimeFormatter.ISO_OFFSET_DATE.format(odt));
    }
}

Output:

2020-11-27Z
2020-11-27T00:00Z
2020-11-27Z
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Thanks, @Arvind Kumar Avinash. I assumed it has to do with the missing time components. So I can use DateTimeFormatter.ISO_OFFSET_DATE only for formatting and never for parsing. Correct? – Buka Nov 27 '20 at 17:24
  • 1
    @Buka - That's correct. In fact, when it comes to formatting, you can 100% rely on the in-built formatters. However, when it comes to parsing a date/date-time string, some inbuilt formatters may not be used directly. This is where `DateTimeFormatterBuilder` comes handy. – Arvind Kumar Avinash Nov 27 '20 at 17:27
  • 1
    @OleV.V. - Thank you for the suggestion. I've updated the answer to incorporate it. – Arvind Kumar Avinash Nov 28 '20 at 07:37