0

I've got three types of ISO dates: yyyy, yyyy-MM, yyyy-MM-dd. In other words, increasingly getting more precise from year to month to day. Should a field be absent, it should be mapped to the lowest possible value (missing day -> first day of the month // missing month -> first month of the year).

A day cannot ever be there without a month, so I thought it would work fine using nested brackets:

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy[-MM[-dd]]");
        LocalDate ld = LocalDate.parse("2019-08-10", dtf); // ok
        ld = LocalDate.parse("2019-08", dtf); // error
        ld = LocalDate.parse("2019", dtf); // error

But alas, the two bottom ones spit out a DateTimeParseException. Is this even possible?

EDIT: Got it. Turns out, as mentioned in the comments, defaults aren't set implicitly. This fixes it:

        DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                .append(DateTimeFormatter.ofPattern("yyyy[-MM[-dd]]"))
                .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
                .toFormatter();
Selbi
  • 813
  • 7
  • 23
  • The pattern is invalid, it is not a regular expression and cannot handle missing values like that. – deHaar Nov 14 '19 at 13:39
  • Then what can handle missing values like that? Is it even possible? – Selbi Nov 14 '19 at 13:43
  • The error should've given you a hint. A `LocalDate` is comprised of all 3 parts. – Sotirios Delimanolis Nov 14 '19 at 13:44
  • And the output was supposed to consist of all three. 2019-08 should be parsed to 2019-08-01. – Selbi Nov 14 '19 at 13:49
  • 1
    Does [this](https://stackoverflow.com/a/45315872/5133585) answer your question? – Sweeper Nov 14 '19 at 13:50
  • In the duplicate, assylias's answer explains why you can't do this (`LocalDate` needs a year, month, and day from the parsed date, which you don't have). Meno's answer shows you how to provide defaults with the `DateTimeFormatter`. – Sotirios Delimanolis Nov 14 '19 at 13:51
  • probably this one https://stackoverflow.com/questions/50023654/java-datetimeformatterbuilder-with-optional-pattern-results-in-datetimeparseexce – Ryuzaki L Nov 14 '19 at 13:57

0 Answers0