0

I tried to covert Oct 31 2015 12:00AM into yyyyMMdd format but it is giving below exception.what could be the reason and solution ? Exception coming while running this code : java.text.ParseException: Unparseable date: "Oct 31 2015 12:00AM"

try{
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");           
        System.out.println("output : "+formatter.format(formatter.parse("Oct 31 2015 12:00AM")));
        }
        catch(Exception e){
            System.out.println("e: "+e);
    }
b22
  • 293
  • 5
  • 10
  • 22
  • 2
    You need one `SimpleDateFormat` to `parse` and another one to `format` - what you have is the latter - now you need to work on the former. Something like: http://stackoverflow.com/questions/3235240/how-to-convert-date-format – assylias Feb 10 '16 at 09:09

1 Answers1

2

You are using the same formatter with yyyyMMdd to parse the date Oct 31 2015 12:00AM which is in the different format i.e. MMMM dd yyyy hh:mma.

You need to define a new formatter to parse the inner date correctly.

Here is a quick code snippet:

public static void main (String[] args)
{
    try{
        SimpleDateFormat xedFormat = new SimpleDateFormat("MMMM dd yyyy hh:mma"); 
        SimpleDateFormat pedFormat = new SimpleDateFormat("yyyyMMdd"); 
        System.out.println("output : "+pedFormat.format(xedFormat.parse("Oct 31 2015 12:00AM")));
    }
    catch(Exception e){
        System.out.println("e: "+e);
}

Output:

output : 20151031
user2004685
  • 9,548
  • 5
  • 37
  • 54
  • 1
    Thanks mate..could you please explain the reason. – b22 Feb 10 '16 at 09:15
  • 1
    `Oct 31 2015 12:00AM` has a different format and hence can't be parse using `yyyyMMdd`. You need to define the correct format i.e. `MMMM dd yyyy hh:mma`. Once parsed it returns you the `Date` Object which can be further formatted to your desired output i.e. `yyyyMMdd`. – user2004685 Feb 10 '16 at 09:17