Search code examples
javastringdate

Java Converting String(day/month/year) format to Date


I am trying to conver the string to a date

String date = "12/31/2012";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        try {
            Date parse = sdf.parse(date);
            System.out.println(parse);
        } catch (ParseException ex) {     
            ex.printStackTrace();
        }

But it appears to me that it is having an Exception. of ParseExpception. why is that? I want to generate a date for 12/31/2012


Solution

  • Date String - 12/31/2012

    It matches with - MM/dd/yyyy

    • d - Day of the month
    • M - Month in year
    • y - Year

    ...

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");