How to convert a String to a Date using SimpleDateFormat?

Shantanu Tomar picture Shantanu Tomar · Mar 26, 2012 · Viewed 319.3k times · Source

I have this code snippet:

DateFormat formatter1;
formatter1 = new SimpleDateFormat("mm/DD/yyyy");
System.out.println((Date)formatter1.parse("08/16/2011"));

When I run this, I get this as the output:

Sun Jan 16 00:10:00 IST 2011

I expected:

Tue Aug 16 "Whatever Time" IST 2011

I mean to say I am not getting the month as expected. What is the mistake?

Answer

Bohemian picture Bohemian · Mar 26, 2012

Try this:

new SimpleDateFormat("MM/dd/yyyy")
  • MM is "month" (not mm)
  • dd is "day" (not DD)

It's all in the javadoc for SimpleDateFormat


FYI, the reason your format is still a valid date format is that:

  • mm is "minutes"
  • DD is "day in year"

Also, you don't need the cast to Date... it already is a Date (or it explodes):

public static void main(String[] args) throws ParseException {
    System.out.println(new SimpleDateFormat("MM/dd/yyyy").parse("08/16/2011"));
}

Output:

Tue Aug 16 00:00:00 EST 2011

Voila!