Converting Exception String to Date
I know this question has been asked a lot, but I cannot find a solution for mine. I have an application where I convert a string to a date and I always get an exception. String that I want to convert, the format 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");
}
+3
source to share
4 answers
"MM" - "two-digit month". You want "MMM" for "abbreviated month name". In addition, you must specify the locale so that it doesn't try to parse it into the custom locale - assuming it really is always 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);
}
}
+8
source to share