Java Calendar And SimpleDateFormat Month Problem

The month seems to come out wrong when using SimpleDateFormat on my Calendar object.  
What am I doing wrong?  When I run my code my results are ...

Sent Date: 05/08/2009
cal.get(Calendar.YEAR): 2009
cal.get(Calendar.MONTH): 4
cal. get(Calendar.DAY_OF_MONTH): 8
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2009);
cal.set(Calendar.MONTH, 4);
cal.set(Calendar.DAY_OF_MONTH, 8);
cal.set(Calendar.HOUR_OF_DAY, 10);
cal.set(Calendar.MINUTE, 10);
cal.set(Calendar.SECOND, 10);
cal.set(Calendar.MILLISECOND, 222);
String sentDate = "";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
if (cal.getTime() != null) {
   sentDate = sdf.format(cal.getTime());
System.out.println("Sent Date: " + sentDate);
System.out.println("cal.get(Calendar.YEAR): " + cal.get(Calendar.YEAR));
System.out.println("cal.get(Calendar.MONTH): " + cal.get(Calendar.MONTH));
System.out.println("cal.get(Calendar.DAY_OF_MONTH): " + cal.get(Calendar.DAY_OF_MONTH));

Open in new window

Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

NahThenLadConnect With a Mentor Commented:
Java sets the months internally with January being 0. When you format the date, Java will display the date in a friendly format, so the numbering gets sorted out to what would be expected from a date, with January being 1 and so on.

You are outputting the date you have formatted as a SimpleDateFormat then outputting the internal value that is being held in the data fields of the calender object you have created, so the values appear to be different, but they are the same.


isarasooConnect With a Mentor Commented:
what values are you getting back fro the month?
tell us what your inputting and the output

Just so you know the months start from 0 i.e.:
jeffman38Author Commented:
Thanks, months start at zero is silly, but what was causing my problem.
in order to fix your issue whatever month you send i.e. 05/08/2009
you will need to dectrement the month field by one
All Courses

From novice to tech pro — start learning today.