我设计的日历表是11*3的显示,加上上一个月和下一个月的选项,对于大月的月份刚好足够,但小月和二月就会有空格。为了方便我在页面上展现日历,我将上一月、下一月、空字符和日期一起封装在了list集合中,使其在页面中直接循环显示出来
能够实现当前日期的显示和人工手动选择日期的功能,在后台都可以得到选择的日期的各项参数,可以进行你想要的操作
在设计和实现日历的时候,我首先想要解决的就是得到今天这个日期在日历表中的显示情况,那必定需要得到今天的日期,还有今天所在月的总天数
对于得到当前所在月的天数的功能,我进行简单的封装,将list集合对象里面的内容补满33个,方便在页面中用循环的方式展现出来
封装选择日期所在月份的日历表代码如下
1 public static List getMonthDays(Date date){
2 Calendar cal = Calendar.getInstance();
3 cal.setTime(date);
4 cal.set(cal.DATE, 1);//日期设置为1号
5 cal.roll(cal.DATE, -1);
6 //roll和add的区别,add会减到上一个月,即1号减1会到上一个月的最后一天,而roll则只在当月进行加减,即1号减1跳转到当月的最后一天,
7 Integer num = cal.get(cal.DAY_OF_MONTH);//获得天数
8 List days = new ArrayList();
9 days.add("《上一月");//日历第一格位置始终为上一月选项
10 for(int i=1;i<=num;i++){
11
12 if(i<10){
13 days.add("0"+i);
14 }else{
15 days.add(i+"");
16 }
17 }
18 int index = 33-days.size();//得到33个位置剩下多少个位置
19 for(int i=1;i<=index;i++){
20 if(i==index){
21 days.add("下一月》");//最后一个位置为下一月选项
22 }else{
23 days.add("");//其它位置添加空字符
24 }
25 }
26 return days;
27
28 }
封装选择日期月份的代码实现了,那我就要实现将当前天在日历表中的日期给展示出来的代码了:
public class MonthDate {
private String chooseMonth; //当前选择的日期月份
private String chooseDay; //当前选择的日期天数
private String chooseYear; //当前选择的日期年份
private List days; //当前选择的日期所在月份的天数,并加上上一个月、下一个月,空字符等内容
public String getChooseMonth() {
return chooseMonth;
}
public void setChooseMonth(String chooseMonth) {
this.chooseMonth = chooseMonth;
}
public String getChooseDay() {
return chooseDay;
}
public void setChooseDay(String chooseDay) {
this.chooseDay = chooseDay;
}
public String getChooseYear() {
return chooseYear;
}
public void setChooseYear(String chooseYear) {
this.chooseYear = chooseYear;
}
public List getDays() {
return days;
}
public void setDays(List days) {
this.days = days;
}
public String monthDay(){
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd");
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy");
chooseMonth = sdf.format(d);
chooseDay = sdf2.format(d);
chooseYear = sdf3.format(d);
//我这边是方便处理,如果觉得这样麻烦,可以不转化时间成String对象,到时候在页面直接通过实现显示
days = MonthNum.getMonthDays(d);//得到当前日期月份的封装对象
return "String";
}