[Solved] Why does SimpleDateFormat() return wrong month?


As noted by other people, there are two problems in your current code:

  • Months are zero based. So, month 7 is August, not July =\
  • Year doesn’t start by default at 1900 but at 1970, but if you set the year by yourself you’ll get as year the same number you’re setting, in this case, 75 (not 1975 as expected).

To solve this, you may create the GregorianCaledar as new GregorianCaledar(1975, 6, 3). Or even better, stop working directly with this class and instead use the abstract class Calendar:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 1975);
calendar.set(Calendar.MONTH, Calendar.JULY);
calendar.set(Calendar.DATE, 3);
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String result = df.format(calendar.getTime());
System.out.println("fmt: " + result);

Why to use Calendar instead of GregorianCalendar? Because you should always work with abstract class/interface instead of class implementation.

solved Why does SimpleDateFormat() return wrong month?