As stated by @OleV.V. in this comment, you can use a pattern with optional sections (to parse the different suffixes st, nd, rd and th).
You must also use a java.util.Locale
to force month names to English. The code will be like this:
String input = "26th May 2017";
DateTimeFormatter parser = DateTimeFormatter
// parse the day followed by st, nd, rd or th (using optional patterns delimited by [])
.ofPattern("dd['st']['nd']['rd']['th'] MMM yyyy")
// force English locale to parse month names
.withLocale(Locale.ENGLISH);
// formatter for dd/MM/yyyy output
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy").withLocale(Locale.ENGLISH);
System.out.println(formatter.format(parser.parse(input))); // 26/05/2017
The code above will work for month names with 3 letters (like May or Aug). If you want to parse the full names (like August or March), just change MMM
to MMMM
:
DateTimeFormatter parser = DateTimeFormatter
// using MMMM to parse full month name (like "August")
.ofPattern("dd['st']['nd']['rd']['th'] MMMM yyyy")
.withLocale(Locale.ENGLISH);
PS: If you want to parse both cases (3-letter or full month names) using the same parser
, you can do this:
DateTimeFormatter parser = DateTimeFormatter
// can parse "March" or "Mar" (MMMM or MMM)
.ofPattern("dd['st']['nd']['rd']['th'][ MMMM][ MMM] yyyy")
.withLocale(Locale.ENGLISH);