java 计算某天在在日历中的位置
背景:最近项目前台要展示一个日历风格数据,需要计算显示位置。
思路:
我找了个没找到java有相关的工具类可以获取这样的日期数据,只好自己写了。
日历显示第一个格子一般是星期天,因此设置日历星期的第1天为星期天,取月的1号的星期数(1-7)作为基数,将当前天(几号)加上基数再减1就是在日历中的索引了,索引范围是1-42 (其实出现最大的是37,即1号索引为7,31号索引为37)
(显示5行的日历)
上代码:
/** * 取日期在日历中的索引 (注意周第一天为星期日) * @param strDate 字符串格式日期 * @param format 格式 * @return 索引值 */ public static int getDayInCalendar(String strDate,String format){ Date date = toDateFromStr(strDate, format); return getDayInCalendar(date); } /** * 取日期在日历中的索引 (注意周第一天为星期日) * @param date 日期 * @return 索引值 */ public static int getDayInCalendar(Date date){Calendar cal = Calendar.getInstance();cal.setFirstDayOfWeek(Calendar.SUNDAY);cal.setTime(date);int firstDayIndex = 0;//几号(1-28,29,30,31)int day = cal.get(Calendar.DAY_OF_MONTH);//1号特殊星期几就是在日历中的索引(1-7) if(day == 1){//星期几(1-7)int weekDay = cal.get(Calendar.DAY_OF_WEEK);return weekDay;}else{//1号所在的索引,也即是1号是星期几firstDayIndex = getDayInCalendar(toDateFromStr(formatDate(cal.getTime(), "yyyy-MM-01"), DAY_FORMAT));}//当前几号+1号索引-1,就是在日历中的位置int index = day + firstDayIndex - 1;return index; } public static void main(String[] args) { String startDay = "2012-09-01"; Calendar cal = Calendar.getInstance(); cal.setTime(DateUtil.toDateFromStr(startDay, DateUtil.DAY_FORMAT));for (int i=0;i<35;i++) {System.out.println(formatDate(cal.getTime(), DAY_FORMAT)+" "+getDayInCalendar(cal.getTime()));cal.add(Calendar.DAY_OF_MONTH, 1);} }
测试:
2012-09-01 72012-09-02 82012-09-03 92012-09-04 102012-09-05 112012-09-06 122012-09-07 132012-09-08 142012-09-09 152012-09-10 162012-09-11 172012-09-12 182012-09-13 192012-09-14 202012-09-15 212012-09-16 222012-09-17 232012-09-18 242012-09-19 252012-09-20 262012-09-21 272012-09-22 282012-09-23 292012-09-24 302012-09-25 312012-09-26 322012-09-27 332012-09-28 342012-09-29 352012-09-30 362012-10-01 22012-10-02 32012-10-03 42012-10-04 52012-10-05 6
图:
http://dl.iteye.com/upload/attachment/0068/9676/44722302-b685-383f-acf0-350d20b51953.png
页:
[1]