---
title: "java 计算某天在在日历中的位置"
author: "pingfan"
date: "2012-06-01T10:46:52Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-06-01T10:47:11Z"
id: 1546341
url: "https://pingfan.iteye.com/blog/1546341"
---

**背景：**
    最近项目前台要展示一个日历风格数据，需要计算显示位置。

**思路：**
    我找了个没找到java有相关的工具类可以获取这样的日期数据，只好自己写了。
    日历显示第一个格子一般是星期天，因此设置日历星期的第1天为星期天，取月的1号的星期数（1-7）作为基数，将当前天（几号）加上基数再减1就是在日历中的索引了，索引范围是1-42 (其实出现最大的是37,即1号索引为7，31号索引为37)
(显示5行的日历)

上代码：

```java

    /**
     * 取日期在日历中的索引 (注意周第一天为星期日)
     * @param strDate 字符串格式日期
     * @param format 格式
     * @return 索引值[1-42]
     */
    public static int getDayInCalendar(String strDate,String format){    	
    	Date date = toDateFromStr(strDate, format);
    	return getDayInCalendar(date);
    }    
    
    
    /**
     * 取日期在日历中的索引 (注意周第一天为星期日)
     * @param date 日期
     * @return 索引值[1-42]
     */
    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);
		}
    }

```



测试：

```java

2012-09-01 7
2012-09-02 8
2012-09-03 9
2012-09-04 10
2012-09-05 11
2012-09-06 12
2012-09-07 13
2012-09-08 14
2012-09-09 15
2012-09-10 16
2012-09-11 17
2012-09-12 18
2012-09-13 19
2012-09-14 20
2012-09-15 21
2012-09-16 22
2012-09-17 23
2012-09-18 24
2012-09-19 25
2012-09-20 26
2012-09-21 27
2012-09-22 28
2012-09-23 29
2012-09-24 30
2012-09-25 31
2012-09-26 32
2012-09-27 33
2012-09-28 34
2012-09-29 35
2012-09-30 36
2012-10-01 2
2012-10-02 3
2012-10-03 4
2012-10-04 5
2012-10-05 6

```


图：


![](http://dl.iteye.com/upload/attachment/0068/9676/44722302-b685-383f-acf0-350d20b51953.png)