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

Android_dev

在这里我想显示日期

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

我可以得到一个月的总天数

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));
}

有人有帮助我的想法吗?

吉恩·B

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

// 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);

如果您实际上想每天打印,则可以将一个月中的某天设置为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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章