Reputation: 518
I'm trying to create a simple calendar app. In general, I want to print the calendar in month view. I am able to find the day and position of the first day of the month. After that, I want to add a day to the calendar and print the next day until I have printed all the days of that month. However, when I add one to the calendar, I don't get 2 (first day is 1), I get 9. Could someone please let me know why it's doing that. Here's what I have so far:
import java.util.Calendar;
import java.util.GregorianCalendar;
enum MONTHS
{
January, February, March, April, May, June, July, August, September, October, November, December;
}
enum DAYS
{
Su, Mo, Tu, We, Th, Fr, Sa;
}
public class MyCalendarTester {
static GregorianCalendar cal = new GregorianCalendar(); // capture today
public static void main(String[] args) {
// TODO Auto-generated method stub
MONTHS[] arrayOfMonths = MONTHS.values();
DAYS[] arrayOfDays = DAYS.values();
System.out.println(" " + arrayOfMonths[cal.get(Calendar.MONTH) - 1] + " " + cal.get(Calendar.YEAR)); //prints the month and year
for(int i = 0; i < arrayOfDays.length; i++){
if(i == 0){
System.out.print(arrayOfDays[i]);
}
else{
System.out.print(" " + arrayOfDays[i]);
}
}//print days of week
System.out.println();
for(int i = 0; i < arrayOfDays.length; i++){
if(!arrayOfDays[i].equals(arrayOfDays[cal.get(Calendar.DAY_OF_WEEK) - 1])){
System.out.println(" ");
}
else{
System.out.print(" " + Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
break;
}
}
cal.add(Calendar.DAY_OF_MONTH, 1);
System.out.println(" " + cal.get(Calendar.DATE));
System.out.println("I think we're done here!");
}
}
Upvotes: 0
Views: 1405
Reputation: 1832
The GregorianCalendar()
constructor without any arguments constructs an instance of the GregorianCalendar
class for todays date. In your code you use this constructor:
static GregorianCalendar cal = new GregorianCalendar(); // capture today
The day of the month, at the time of posting in 8. 8+1=9
To create a GregorianCalendar with the day of the month initialized to 1 you need to use GregorianCalendar(int year,int month,int dayOfMonth)
. As stated in the javadocs, this constructor
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
static GregorianCalendar cal = new GregorianCalendar(2015,5,1);
Upvotes: 2
Reputation: 3035
The calendar object you're adding one to is static GregorianCalendar cal = new GregorianCalendar();
- that's why it said 9 (it is March, 9th)
Upvotes: 1