Colm Fitzpatrick Colm Fitzpatrick - 1 year ago 86
Java Question

Java calender skipping first month

I am currently trying to make a Java program that simply prints out the dates for each day of the year. It work perfectly for every month in the year apart for January. Could anyone suggest what I might be doing wrong? Please find code below.

String date;

Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 0);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int maxMon = cal.getActualMaximum(Calendar.MONTH);
SimpleDateFormat df = new SimpleDateFormat("dd_MM_yy");
for (int j = 0; j < maxMon; j++){
for (int i = 0; i < maxDay; i++) {
cal.set(Calendar.DAY_OF_MONTH , i);
date = df.format(cal.getTime());

Answer Source

First you'd need to get int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); inside the month loop.

Next, keep in mind that MONTH and DAY_OF_MONTH have different bases: MONTH is 0-based and thus maxMon will be 11. DAY_OF_MONTH is 1-based and thus maxDay will be in the range 28-31.

So if you change your loops accordingly (start at j = 0 and i = 1 and use j <= maxMon and i <= maxDay) your results should be fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download