0

Is there a way do write a DateTimeFormatter pattern that parser "either" one of two optional parts? Something like (MMMM-d-(yy OR yyyy))?

For an example:

val formatter = DateTimeFormatter.ofPattern("MMMM-d-[yyyy][yy]");
System.out.println(formatter.parse("June-27-2022")); // {},ISO resolved to 2022-06-27
System.out.println(formatter.parse("June-27-22")); // {},ISO resolved to 2022-06-27
System.out.println(formatter.parse("June-27-")); // {MonthOfYear=6, DayOfMonth=27},ISO

I want to parse either the short (yy) or long (yyyy) year format. The problem with my pattern is that the last example gets parsed without either of these optional parts of the pattern defined.

alturkovic
  • 990
  • 8
  • 31
  • 1
    Create a regex to test each pattern. When the pattern matches, use that formatter. – RobOhRob Jun 27 '22 at 15:02
  • 1
    Just parse into a type that requires a year, for example `LocalDate.parse("June-27-2022", formatter)`. Then trying `"June-27-"` will fail with an exception. – Ole V.V. Jun 27 '22 at 16:45
  • Related: [Java 8 DateTimeFormatter two digit year 18 parsed to 0018 instead of 2018?](https://stackoverflow.com/questions/48156022/java-8-datetimeformatter-two-digit-year-18-parsed-to-0018-instead-of-2018). Also [this](https://stackoverflow.com/questions/23488721/how-to-check-if-string-matches-date-pattern-using-time-api), and there are more. – Ole V.V. Jun 27 '22 at 16:47
  • @OleV.V. Could you post this as an answer so I can accept it? This is the closest to what I was looking for, thank you. – alturkovic Jun 28 '22 at 07:17
  • 1
    I am no longer contributing answers to Stack Overflow (for reasons that I try to explain in [my profile](https://stackoverflow.com/users/5772882/ole-v-v)). Feel free to post it as an answer yourself, and I shall be happy to upvote. – Ole V.V. Jun 28 '22 at 13:40

2 Answers2

2

One option is to create a list of multiple formatters each with their own pattern. Try each one in turn until one of them succeeds. If none successfully parses the input string, then give an error.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
1

I went with the solution proposed by @OleV.V.:

val formatter = DateTimeFormatter.ofPattern("MMMM-d-[yyyy][yy]");
System.out.println(LocalDate.parse("June-27-2022", formatter)); 
System.out.println(LocalDate.parse("June-27-22", formatter)); 
System.out.println(LocalDate.parse("June-27-", formatter)); // throws an Exception
alturkovic
  • 990
  • 8
  • 31