如何使用日历类获得一个月内的所有日期?

And*_*dev 4 java java.util.calendar

在这里,我希望显示日期

2013-01-01,
2013-01-02,
2013-01-03,
.
.
...etc
Run Code Online (Sandbox Code Playgroud)

我可以在一个月内得到总天数

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));
}
Run Code Online (Sandbox Code Playgroud)

有没有人有想法帮助我?

小智 9

如果您只想获得一个月内的最大天数,则可以执行以下操作.

// 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);
Run Code Online (Sandbox Code Playgroud)

如果您实际上想要每天打印,那么您可以将月中的日期设置为1并继续在循环中添加一天,直到月份更改为止.

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);
}
Run Code Online (Sandbox Code Playgroud)


Ole*_*.V. 5

现代答案:不要使用Calendar. 使用java.time,现代 Java 日期和时间 API。

YearMonth ym = YearMonth.of(2013, Month.JANUARY);
LocalDate firstOfMonth = ym.atDay(1);
LocalDate firstOfFollowingMonth = ym.plusMonths(1).atDay(1);
firstOfMonth.datesUntil(firstOfFollowingMonth).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)

输出(缩写):

2013-01-01
2013-01-02
2013-01-03
…
2013-01-30
2013-01-31
Run Code Online (Sandbox Code Playgroud)

datesUntil为我们提供了日期的流,直到指定的结束日期排他性,所以当我们给它下一个月的1日,我们得到确切的所有月份的有关日期。在此示例中,截至并包括 1 月 31 日。

链接: Oracle 教程:解释如何使用java.time.