Search code examples
javajava.util.calendar

How to get all the dates in a month using calender class?


Here I want to display dates like

2013-01-01,
2013-01-02,
2013-01-03,
.
.
...etc

I can get total days in a month

private int getDaysInMonth(int month, int year) {
  Calendar cal = Calendar.getInstance();  // or pick another time zone if necessary
  cal.set(Calendar.MONTH, month);
  cal.set(Calendar.DAY_OF_MONTH, 1);      // 1st day of month
  cal.set(Calendar.YEAR, year);
  cal.set(Calendar.HOUR, 0);
  cal.set(Calendar.MINUTE, 0);
  Date startDate = cal.getTime();

  int nextMonth = (month == Calendar.DECEMBER) ? Calendar.JANUARY : month + 1;
  cal.set(Calendar.MONTH, nextMonth);
  if (month == Calendar.DECEMBER) {
     cal.set(Calendar.YEAR, year + 1);
  }
  Date endDate = cal.getTime();

  // get the number of days by measuring the time between the first of this
  //   month, and the first of next month
  return (int)((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
}

Does anyone have an idea to help me?


Solution

  • If you only want to get the max number of days in a month you can do the following.

    // Set day to one, add 1 month and subtract a day
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.DAY_OF_MONTH, 1); 
    cal.add(Calendar.MONTH, 1);
    cal.add(Calendar.DAY_OF_MONTH, -1);
    return cal.get(Calendar.DAY_OF_MONTH);
    

    If you actually want to print every day then you can just set the day of month to 1 and keep adding a day in a loop until the month changes.

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.DAY_OF_MONTH, 1); 
    int myMonth=cal.get(Calendar.MONTH);
    
    while (myMonth==cal.get(Calendar.MONTH)) {
      System.out.print(cal.getTime());
      cal.add(Calendar.DAY_OF_MONTH, 1);
    }