This question already has an answer here:
Is there any java library available to parse language specific ordinal indicator/suffix?
I have a date value like the following: 26th May 2017
. I want to convert this to 26/05/2017
. Could anyone please guide me how to do?
You can parse this format directly to a Java 8
LocalDate
using a custom date format:This is using the version of
DateTimeFormatter.appendText
which accepts a map that is used to map the day string.You will need to fill in all the missing entries in
ORDINAL_DAYS
that I have left out for brevity.Assuming you don’t need very strict input validation, since you are converting from the format with
th
on the number (orst
ornd
in31st
,2nd
and more), I suggest you simply remove those two letters first. A regex may do that:The result is
This works if your input contains a three letter abbreviation for the month, like Apr, May or Jun. To accept a full month name instead (April, May, June), you need 4 Ms instead of 3 in the format pattern:
d MMMM uuuu
.Assuming you are asking about Java, this link: https://www.mkyong.com/java/how-to-convert-string-to-date-java/ May help you.
The overall gist is:
Where
dd/MM/yyyy
is a date formatter that would give you26/05/2017
.Hope this helps!
EDIT: Also see http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html for a full list of the different pattern letters for
SimpleDateFormat
.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: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
toMMMM
:PS: If you want to parse both cases (3-letter or full month names) using the same
parser
, you can do this: