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(); 
7
  • The pattern is invalid, it is not a regular expression and cannot handle missing values like that. Commented Nov 14, 2019 at 13:39
  • Then what can handle missing values like that? Is it even possible? Commented Nov 14, 2019 at 13:43
  • The error should've given you a hint. A LocalDate is comprised of all 3 parts. Commented Nov 14, 2019 at 13:44
  • And the output was supposed to consist of all three. 2019-08 should be parsed to 2019-08-01. Commented Nov 14, 2019 at 13:49
  • 1
    Does this answer your question? Commented Nov 14, 2019 at 13:50

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.