Search code examples
javadatesimpledateformat

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


How can I perform this conversion in Java?

Currently, I'm 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 results in an incorrect format. It gives me the following output:

Friday, February 1, 2013 > 2013-01-04
Thursday, January 31, 2013 > 2013-01-03

Solution

  • You're using DD in your parsing part, which is the day of year. You want dd instead. You also probably want yyyy (year) instead of YYYY (week year). (In most cases they're the same value, but not always.)