Question

So I have this String: "Tue Apr 15 00:00:00 IDT 2014" or "Apr 15 2014" after I change it by split it. And I want to convert it to this format: "yyyy-MM-dd" but when I i get this message:

java.text.ParseException: Unparseable date: "Apr 15 2014"

Here is my full code:

DateFormat or=new SimpleDateFormat("MMM d yyyy");
            DateFormat tr=new SimpleDateFormat("yyyy-MM-dd");
           String str="Apr 15 2014";

            System.out.println(str);
            //String strs[]=str.split(" ");
            //String newDay=strs[1]+" "+strs[2]+" "+strs[5];
            //System.out.println(newDay);
            try {
                Date d1=or.parse(str);
                System.out.println(d1);
            } catch (ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

Thanks to helpers :)

Was it helpful?

Solution

The month field value in the input String may not match that from your default Locale. Try

DateFormat format = new SimpleDateFormat("MMM d yyyy", Locale.ENGLISH);
...
Date date = format.parse(str);

Note: Rather than manipulating the original String it could have been parsed directly with

DateFormat format = 
    new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);

OTHER TIPS

the code:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
    public static Date getDateFromString(String format, String dateStr) {

            DateFormat formatter = new SimpleDateFormat(format);
            Date date = null;
            try {
                date = (Date) formatter.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            return date;
        }

-----------------

    public static String getDate(Date date, String dateFormat) {
        DateFormat formatter = new SimpleDateFormat(dateFormat);
        return formatter.format(date);
    }

I made the following change to your code:

        **DateFormat or = new SimpleDateFormat("MMM dd yyyy");**
    new SimpleDateFormat("yyyy-MM-dd");
    String str = "Apr 15 2014";

    System.out.println(str);
    //String strs[]=str.split(" ");
    //String newDay=strs[1]+" "+strs[2]+" "+strs[5];
    //System.out.println(newDay);
    try {
        Date d1 = or.parse(str);
        System.out.println(d1);
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

And I got the following output:

Apr 15 2014

Tue Apr 15 00:00:00 BST 2014

java.util.Date  ss1=new Date("Tue Apr 15 00:00:00 IDT 2014");
SimpleDateFormat formatter5=new SimpleDateFormat("yyyy-MM-dd");
String formats1 = formatter5.format(ss1);
System.out.println(formats1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top