I have a String "Saturday, Oct, 25th, 11:40"
What format does this date has? How can I parse the ordinal indicator?
Here is how i want to convert it
private String changeDateFormat(String stringDate){
DateFormat dateFormat = new SimpleDateFormat("DD, MM, ddth, hh:mm");
try {
Date date = dateFormat.parse(stringDate);
dateFormat = new SimpleDateFormat("ddMMMyyyy");
stringDate=dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return stringDate.toUpperCase();
}
SimpleDateFormat
doesn't seem to easily handle day numbers followed by "st" "th" etc. A simple solution would be remove that part of the original string. E.g.
int comma = original.lastIndexOf(',');
String stringDate =
original.substring(0, comma - 2) +
original.substring(comma + 1);
After that just use this format on stringDate
:
SimpleDateFormat("EE, MM, dd, hh:mm")
Hope this program solve your problem.
public class Test
{
public static void main(String[] args) {
System.out.println(new Test().getCurrentDateInSpecificFormat(Calendar.getInstance()));
}
private String getCurrentDateInSpecificFormat(Calendar currentCalDate) {
String dayNumberSuffix = getDayNumberSuffix(currentCalDate.get(Calendar.DAY_OF_MONTH));
DateFormat dateFormat = new SimpleDateFormat("E, MMM, dd'"+ dayNumberSuffix +"', HH:mm");
return dateFormat.format(currentCalDate.getTime());
}
private String getDayNumberSuffix(int day) {
if (day >= 11 && day <= 13) {
return "th";
}
switch (day % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
}
The java doc has lot of information on how to parse a date from String in different formats :
SimpleDateFormat Java Doc
You can try with this, but play around this and refer java doc until you are able to solve your problem :
DateFormat dateFormat = new SimpleDateFormat("E, MMM, dd'th' HH:mm");
Date date = dateFormat.parse("Saturday, Oct, 25th, 11:40");
Try different combinations, that way you will learn more about SimpleDateFormat and how it works with different formats.
One solution would be to parse the parameter in order to know which pattern to use:
private String changeDateFormat(String stringDate) {
DateFormat dateFormat;
if (stringDate.matches("^([a-zA-Z]+, ){2}[0-9]+st, [0-9]{2}:[0-9]+{2}")) {
dateFormat = new SimpleDateFormat("E, MMM, dd'st', HH:mm");
} else if (stringDate.matches("^([a-zA-Z]+, ){2}[0-9]+nd, [0-9]{2}:[0-9]+{2}")) {
dateFormat = new SimpleDateFormat("E, MMM, dd'nd', HH:mm");
} else if (stringDate.matches("^([a-zA-Z]+, ){2}[0-9]+rd, [0-9]{2}:[0-9]+{2}")) {
dateFormat = new SimpleDateFormat("E, MMM, dd'rd', HH:mm");
} else {
dateFormat = new SimpleDateFormat("E, MMM, dd'th', HH:mm");
}
try {
Date date = dateFormat.parse(stringDate);
dateFormat = new SimpleDateFormat("ddMMMyyyy");
stringDate = dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return stringDate.toUpperCase();
}
This might need some optimisation, but it gives the idea.