How to convert the date format 1st-May-2013
to 2013-05-01
, 10th-Jun-2002
to 2002-06-10
and 2nd-Apr-1996
to 1996-04-02
.
Notice that the input dates contain the ordinal part (e.g. 1st
etc).
How to convert the date format 1st-May-2013
to 2013-05-01
, 10th-Jun-2002
to 2002-06-10
and 2nd-Apr-1996
to 1996-04-02
.
Notice that the input dates contain the ordinal part (e.g. 1st
etc).
Ordinal part is not considered by the existings formatter of LocalDate
which is DateTimeFormatter
, so you need to remove the ordinal part, and then parse with the good pattern
public static void main(String[] args){
String[]strs = {"1st-May-2013", "10th-Jun-2002", "2nd-Apr-1996"};
for(String str : strs){
LocalDate d = ordinalStringToDate(str);
System.out.println(d);
}
}
private static LocalDate ordinalStringToDate(String str){
return LocalDate.parse(str.replaceAll("(st|nd|rd|th)", ""),
DateTimeFormatter.ofPattern("d-MMM-yyyy"));
}
Pattern :
d
is for the day numberMMM
is for the month short litteral (MMMM
if for full month name)yyyy
fot the year numberWorkable Demo