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


You have to see what exactly says ParseExeption

. Parsing your string should be done by computers, not humans.



Anyway, the first problem I see is that you have to write three M

instead of two EEE, MMM d, yyyy

.

0


source


class Check{
 public static void main(String args[])throws ParseException{
 String str="Mon, Aug 4, 2014";
 java.util.Date date=new SimpleDateFormat("EEE, MMM d, yyyy",Locale.ENGLISH).parse(str);
 System.out.println(date);
 }
}

      

0


source


There is no digital in your string month. Analysis string

Date d = new SimpleDateFormat("EEE, MMM d, yyy",Locale.US).parse(theStringToConvert);

      

0


source







All Articles