I store in a database:
- a week as
yyyyWww, that is2023W10is 10th week of 2023 - a month as
2023M10meaning October 2023
I can use yyyy'W'ww and yyyy'M'MM formats in SimpleDateFormat.
DateTimeFormatter gives DateTimeParseException in these cases. Seems DateTimeFormatter will only accept a complete date (year+month+day) with limited text (dash, slash, period)
What am I missing here?
I have tried yyyy'W'ww and yyyy'M'MM formats in dateTimeFormatter, both give parseexceptions.
You will need to use a
DateTimeFormatterBuilderto apply defaults along with your pattern.A simple approach would be to declare all known formats ahead of time and loop through them. If you want to eliminate the looping, you could check if the string contains a "W" and call the week parser, or an "M" and call the month parser.
Please note that
YYYY(upper-case) denotes a week-based year, vsyyyy(lower-case) an era (normal 365 day year).Output:
Update
If you want to remove the loop and exception handling, you could check to see if the input string contains an "M" or "W" as explained above.