1

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

1

4 Answers 4

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");
Sign up to request clarification or add additional context in comments.

Comments

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");

Comments

2

java.time

In modern Java, use only the java.time classes for date-time work. Never use Calendar nor SimpleDateFormat.

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MM/dd/uuuu" ) ;
LocalDate ld = LocalDate.parse ( "12/31/2012" , f ) ;

Generate text in standard ISO 8601 format, YYYY-MM-DD, by simply calling toString.

String output = ld.toString() ;

Comments

1

If You could use Joda time

String dateStr = "11/15/2013";
Date date = DateTimeFormat.forPattern("dd/MM/yyyy").parseDateTime(dateStr).toDate();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.