Convert "Friday February 1, 2013" to "2013-02-01"

How can I do this conversion in Java?

I am currently doing:

public static String formatDate(String strDateToFormat) {
    try {
        SimpleDateFormat sdfSource = new SimpleDateFormat("EEEE, MMMM DD, YYYY");
        Date date = sdfSource.parse(strDateToFormat);
        SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
        return sdfDestination.format(date);
    } catch (ParseException pe) {
        System.err.println("Parse Exception : " + pe);
    }

    return null;
}

However, this leads to the wrong format. It gives me the following result:

Friday, February 1, 2013 > 2013-01-04
Thursday, January 31, 2013 > 2013-01-03
+5
source share
2 answers

You use DDin your parsing part, which is the day of the year. Instead you want to DD. You probably also want yyyy(year) instead of yyyy(week). (In most cases, they have the same meaning, but not always).

+9
source

You use DD in your parsing part, which is the day of the year. Instead, you want dd. Change also YYYY to yyyy.

Here you can find all the templates.

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

+3

All Articles