Convert Date time in "April 6th, 2012 " format

SimpleDateFormat format = new SimpleDateFormat("d");
String date = format.format(new Date());

if(date.endsWith("1") && !date.endsWith("11"))
    format = new SimpleDateFormat("EE MMM d'st', yyyy");
else if(date.endsWith("2") && !date.endsWith("12"))
    format = new SimpleDateFormat("EE MMM d'nd', yyyy");
else if(date.endsWith("3") && !date.endsWith("13"))
    format = new SimpleDateFormat("EE MMM d'rd', yyyy");
else 
    format = new SimpleDateFormat("EE MMM d'th', yyyy");

String yourDate = format.format(new Date());

Try this, This looks like some static but works fine...


You could subclass SimpleDateFormat and override format, and use a simple utility function that takes in a String or Integer and returns a String with either "nd" or "st" attached...something like:

if (initialDate.equals("2") || initialDate.equals("22"){
    return initialDate += "nd";
}else if {initialDate.equals("3") || initialDate.equals("23"){
    return initialDate += "rd";
}else{
    return initialDate += "th";
}

Here you go:

/**
 * Converts Date object into string format as for e.g. <b>April 25th, 2012</b>
 * @param date date object
 * @return string format of provided date object
 */
public static String getCustomDateString(Date date){
    SimpleDateFormat tmp = new SimpleDateFormat("MMMM d");

    String str = tmp.format(date);
    str = str.substring(0, 1).toUpperCase() + str.substring(1);

    if(date.getDate()>10 && date.getDate()<14)
        str = str + "th, ";
    else{
        if(str.endsWith("1")) str = str + "st, ";
        else if(str.endsWith("2")) str = str + "nd, ";
        else if(str.endsWith("3")) str = str + "rd, ";
        else str = str + "th, ";
    }

    tmp = new SimpleDateFormat("yyyy");
    str = str + tmp.format(date);

    return str;
}

Sample:

Log.i("myDate", getCustomDateString(new Date()));

April 25th, 2012

Tags:

Android