下面详细讲解了自定义日历控件中,如何获取日期数据。
private void calculate() {
// 例如,今天是2015-08-27
List<Integer> dateList = new ArrayList<Integer>();
// calendar.getTime() : "Sat Aug 01 12:00:00 GMT-04:00 2015"
Calendar calendar = Calendar.getInstance();
// 设置完后,calendar = 2015/08/01
calendar.set(Calendar.DAY_OF_MONTH, 1);
// DAY_OF_WEEK:获得的是calendar在一周中的第几天,数值范围1~7,详细说明请参考本文后面。
// 获得的dayInWeek = 7
int dayInWeek = calendar.get(Calendar.DAY_OF_WEEK);
// 计算8月1号前面的空白数据
int nullDataRange = dayInWeek - 1;
for (int i = 0; i < nullDataRange; i++) {
dateList.add(0);
}
// 获取一个月的最大值,即 maxDay = 31
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = 1; i <= maxDay; i++) {
dateList.add(i);
}
// 获取到的List如下:
//[ 0, 0, 0, 0, 0, 0, 1,
// 2, 3, 4, 5, 6, 7, 8,
// 9, 10, 11, 12, 13, 14, 15,
// 16, 17, 18, 19, 20, 21, 22,
// 23, 24, 25, 26, 27, 28, 29,
// 30, 31 ]
Log.d("TAG", Arrays.toString(dateList.toArray()));
}
DAY_OF_WEEK的官方解释
public static final int DAY_OF_WEEK
Field number for get and set indicating the day of the week. This field
takes values SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and
SATURDAY.See Also
- SUNDAY
- MONDAY
- TUESDAY
- WEDNESDAY
- THURSDAY
- FRIDAY
- SATURDAY Constant Value: 7 (0x00000007)
getActualMaximum()
public int getActualMaximum (int field)
Returns the maximum value of the given field for the current date. For example, the maximum number of days in the current month.