I know this question has been asked a lot but I can't find the solution to mine. I have an application where I'm converting a string to a date and I always catch the exception. The string that I want to convert is in the format: 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");
}
"MM" is "two digit month". You want "MMM" for "abbreviated name of month". Additionally, you should specify the locale so that it doesn't try to parse it in the user's locale - assuming it really will always be 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);
}
}
See more on this question at Stackoverflow