String.replaceAll() and DateTimeFormatter
private static final DateTimeFormatter DATE_PARSER
= DateTimeFormatter.ofPattern("[-]d-M-u[-]", Locale.ROOT);
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern("dd-MM-uuuu", Locale.ROOT);
public static void parseAndFormat(String input) {
String adapted = input.replaceAll("\\W+", "-");
System.out.println("Adapted input string: " + adapted);
LocalDate date = LocalDate.parse(adapted, DATE_PARSER);
String formatted = date.format(DATE_FORMATTER);
System.out.println("Formatted: " + formatted);
}
The above method parses your string:
parseAndFormat("25-06-2008");
Output:
Adapted input string: 25-06-2008
Formatted: 25-06-2008
It’s very tolerant to which delimiters the users decides to use between the numbers, and also before or after them if any:
parseAndFormat("$5///7 2008 ?");
Adapted input string: -5-7-2008-
Formatted: 05-07-2008
How it works: input.replaceAll("\\W+", "-")
substitutes any run of non-word characters — everything but letters a through z and digits 0 through 9 — with a single hyphen. No one is interested in seeing the adapted input string, I am only printing it for you to understand the process better. The formatter I use for parsing accepts an optional hyphen first and last. The square brackets in the format pattern denote optional parts. It also accepts day and month in 1 or 2 digits and year in up to 9 digits. I use a separate formatter for formatting so I can control that day and month come in 2 digits and there are no hyphens before nor after.