要获取本月的日历表,可以使用Java中的Calendar类来实现。下面是详细步骤:
1.获取当前月份的第一天
我们可以使用Calendar类的getActualMinimum()方法,将日历字段设置为该字段可能的最小值,例如我们将日历字段设置为月份的最小值,即Calendar.MONTH,然后使用getActualMinimum(Calendar.DATE)方法获取当前月份的第一天的日期。代码如下:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DATE));
Date firstDayOfMonth = calendar.getTime();
2.获取当前月份的最后一天
类似地,我们可以使用getActualMaximum(Calendar.DATE)方法获取当前月份的最后一天,代码如下:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DATE));
Date lastDayOfMonth = calendar.getTime();
3.获取当前月份的所有日期
要获取当前月份的所有日期,我们需要循环处理从当前月份的第一天到最后一天之间的日期。代码如下:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DATE));
Date firstDayOfMonth = calendar.getTime();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DATE));
Date lastDayOfMonth = calendar.getTime();
calendar.setTime(firstDayOfMonth);
while (!calendar.getTime().after(lastDayOfMonth)) {
Date currentDate = calendar.getTime();
System.out.println(currentDate);
calendar.add(Calendar.DATE, 1);
}
示例输出:
Tue Sep 01 00:00:00 CST 2020
Wed Sep 02 00:00:00 CST 2020
Thu Sep 03 00:00:00 CST 2020
Fri Sep 04 00:00:00 CST 2020
Sat Sep 05 00:00:00 CST 2020
Sun Sep 06 00:00:00 CST 2020
Mon Sep 07 00:00:00 CST 2020
Tue Sep 08 00:00:00 CST 2020
Wed Sep 09 00:00:00 CST 2020
Thu Sep 10 00:00:00 CST 2020
Fri Sep 11 00:00:00 CST 2020
Sat Sep 12 00:00:00 CST 2020
Sun Sep 13 00:00:00 CST 2020
Mon Sep 14 00:00:00 CST 2020
Tue Sep 15 00:00:00 CST 2020
Wed Sep 16 00:00:00 CST 2020
Thu Sep 17 00:00:00 CST 2020
Fri Sep 18 00:00:00 CST 2020
Sat Sep 19 00:00:00 CST 2020
Sun Sep 20 00:00:00 CST 2020
Mon Sep 21 00:00:00 CST 2020
Tue Sep 22 00:00:00 CST 2020
Wed Sep 23 00:00:00 CST 2020
Thu Sep 24 00:00:00 CST 2020
Fri Sep 25 00:00:00 CST 2020
Sat Sep 26 00:00:00 CST 2020
Sun Sep 27 00:00:00 CST 2020
Mon Sep 28 00:00:00 CST 2020
Tue Sep 29 00:00:00 CST 2020
Wed Sep 30 00:00:00 CST 2020
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java获取本月日历表的方法 - Python技术站