Java – Convert string to date exception

Convert string to date exception… here is a solution to the problem.

Convert string to date exception

I

know this question has been asked a lot, but I can’t find a solution that works for me. I have an app where I convert strings to dates, but I always catch exceptions. The format of the string I want to convert is: Mon, Aug 4, 2014. Here is my code :

try {
    Date d = new SimpleDateFormat("EEE, MM d, yyyy").parse(theStringToConvert);
    Log.i("MyApp", "Date: " + d);
}
catch (ParseException e){
    Log.i("EXCEPTION", "Cannot parse string");
}

Solution

“MM” is “Two-digit month”. You need “MMM” as the “abbreviated name of the month”. Also, you should specify the locale so it doesn’t try to resolve it in the user’s locale – assuming it really will always be in English:

import java.util.*;
import java.text.*;

public class Test {
    public static void main(String[] args) throws Exception {
        String text = "Mon, Aug 4, 2014";
        DateFormat format = new SimpleDateFormat("EEE, MMM d, yyy",
                                                  Locale.US);
        Date date = format.parse(text);
        System.out.println(date);
    }
}

Related Problems and Solutions