先看图
代码如下:
public void printByYearAndMonth(int year, int month) {
System.out.println();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
List<Integer> headerList = null;
List<Integer> endList = null;
String firstday, lastday;
// 获取前月的第一天
Calendar cale = Calendar.getInstance();
cale.set(Calendar.YEAR, year);
cale.set(Calendar.MONTH, month);
cale.add(Calendar.MONTH, 0);
cale.set(Calendar.DAY_OF_MONTH, 1);
int dayOfWeek = cale.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SUNDAY) {
headerList = new ArrayList<>();
for (int i = 1; i < dayOfWeek; i++) {
headerList.add(0);
}
}
firstday = format.format(cale.getTime());
// 获取前月的最后一天
// cale = Calendar.getInstance();
cale.add(Calendar.MONTH, 1);
cale.set(Calendar.DAY_OF_MONTH, 0);
int lastDayOfMonth = cale.get(Calendar.DAY_OF_MONTH);
lastday = format.format(cale.getTime());
System.out.println("本月第一天和最后一天分别是 : " + firstday + " and " + lastday);
List<Integer> totalList = new ArrayList<>();
if (headerList != null) {
totalList.addAll(headerList);
}
for (int i = 1; i <= lastDayOfMonth; i++) {
totalList.add(i);
}
for (int i = 0; i < totalList.size(); i++) {
if (i != 0 && i % 7 == 0) {
System.out.println();
}
System.out.print(" " + totalList.get(i));
}
}