Question

I am trying to parse the date in a particular custom format.

WEDNESDAY 25th JAN 2012 - 12:44:07 PM

like this..

I created a SimpleDateFormat for this..

SimpleDateFormat sdf = new SimpleDateFormat("EEEE DD MMM YYYY - HH:MM:SS aa" );

the problem is the literal for the days. it is coming like 25th, 23rd, 02nd.I am getting exception for this thing...

help how to overcome this problem.

Was it helpful?

Solution

You could split the date string you're trying to parse into parts and remove the offending two letters in the following way:

String text = "WEDNESDAY 21st JAN 2012 - 12:44:07 PM";
String[] parts = text.split(" ", 3);  // we only need 3 parts. No need splitting more
parts[1] = parts[1].substring(0, 2);
String parseableText = String.format("%s %s %s", parts[0], parts[1], parts[2]);  
SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd MMM yyyy - hh:mm:ss aa" );

try {
    java.util.Date dt = sdf.parse(parseableText);
} catch (ParseException e) {
    e.printStackTrace();
}

Your parse string had some errors in it as well. Case is important for the date and time ptterns. See the SimpleDateFormat javadoc for a reference.

OTHER TIPS

You can remove the literal for the day using a regex like this.

String dateString = "WEDNESDAY 25th JAN 2012 - 12:44:07 PM";
SimpleDateFormat format = new SimpleDateFormat("EEEEEEE dd MMM yyyy - HH:mm:ss aa", new Locale("EN"));
dateString = dateString.replaceAll("(.*[0-9]{1,2})(st|nd|rd|th)(.*)", "$1$3");
Date parsedDate = format.parse(dateString);

System.out.println(parsedDate);

(Ignore the Locale, i'm from somewhere else :) )

You are going to have to manually do it somehow.

e.g. A method as follows:

public static String makeItParseable(String dateStr) {
    if(dateStr.contains("st ")) {
        return dateStr.replace("st ", " ");
    } else if(dateStr.contains("nd ")) {
        return dateStr.replace("nd ", " ");
    } else if(dateStr.contains("rd ")) {
        return dateStr.replace("rd ", " ");
    } else {
        return dateStr.replace("th ", " ");
    }
}

And use it make the input string parseable:

String dateStr = "WEDNESDAY 1st JAN 2012 - 12:44:07 PM";
dateStr = makeItParseable(dateStr);
DateFormat dateFormat = new SimpleDateFormat("EEEE dd MMM yyyy - hh:mm:ss a");
Date date = dateFormat.parse(dateStr);

Add ".th" to the format string, following what people stated in this thread

How do you format the day of the month to say "11th", "21st" or "23rd" in Java? (ordinal indicator)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top