0

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

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
user962206
  • 15,637
  • 61
  • 177
  • 270

3 Answers3

7

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");
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
2

format for month is MM not mm and also your should should delimit with - and not / as your formatter delimiter is / and your format should match your date atring.

date 12-31-2012
fmt  MM-dd-yyyy


String date = "12-31-2012";
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

If You could use Joda time

String dateStr = "11/15/2013";
Date date = DateTimeFormat.forPattern("dd/MM/yyyy").parseDateTime(dateStr).toDate();
Igor Vuković
  • 742
  • 12
  • 25