javadatedate-formatsimpledateformat

Java DateFormat and SimpleDateFormat returning a date that is incorrect


Today is Tuesday, February 9, 2010 and when I print the date I get the wrong date:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

Date today = formatter.parse(String.format("%04d-%02d-%02d",
        Calendar.getInstance().get(Calendar.YEAR),
        Calendar.getInstance().get(Calendar.MONTH),
        Calendar.getInstance().get(Calendar.DAY_OF_MONTH)));

System.out.println("Today is " + today.toString());

The print line results in: "Today is Sat Jan 09 00:00:00 CST 2010"

It most certainly is not Saturday Jan 09, it's Tuesday Feb 09. I'm assuming I'm doing something wrong, so can anybody let me know what's wrong here? Do I have to manually set the day of week?

Update Note: I don't want to initialize today with new Date() because I want the hours, minutes, seconds and milliseconds initialized to 0. This is necessary so I can compare a user input date with today: if the user inputs today's date and I use the formatter to construct a Date object, then if I initialize today with new Date() and I compare the two dates- today will be after the user selected date (which is incorrect). Thus I need to initialize today at the beginning of the day without the hr/min/sec/ms.


Solution

  • Confusingly, Calendar months count from 0 (January) to 11 (December), so you're passing "2010-01-09" to formatter.parse() when you extract the MONTH field from the Calendar.

    There's a discussion of this in a related SO question.