最近做关于报刊发行的项目,需要根据报刊的刊期种类(即为日报、周报还是月刊)计算该报刊的出版日期,让我好好熟悉了一下JAVA中的Calendar接口,把我研究两天的成果记录下来。
/** */
/**
* 计算日报的出版日期(ok)
*
* @param year
* 年份
* @return
*/
private
static
Set
<?>
getEveryday(String year)

...
{
Set<Date> set = new TreeSet<Date>();
Calendar cal = Calendar.getInstance();
// 设置日期为某年的第一天并放入集合
cal.set(Integer.parseInt(year), 0, 1);
set.add(cal.getTime());

// 获取当年的最后一天

int endDay = cal.getActualMaximum(Calendar.DAY_OF_YEAR);

for (int day = 1; day < endDay; day++)

...{
cal.add(Calendar.DAY_OF_YEAR, 1);
set.add(cal.getTime());
}
return set;
}


/** */
/**
* 出版日期中的数字代表日(ok)

* 011020-1日、10日、20日
*
* @param year
* 年份
* @param publishDate
* 出版日期
* @param months
* 月份数组
* @return
*/
private
static
Set
<?>
digitsRepresentDay(String year, String publishDate,
int
[] months)

...
{
Set<Date> set = new TreeSet<Date>();
for (int i = 0; i < months.length; i++)

...{
int month = months[i];// 取得月份

// 拼接年月字符串,格式为:年份/月份/
String yearAndMonthStr = year + "/" + month + "/";
for (int j = 0; j < publishDate.length(); j = j + 2)

...{
try

...{
String day = StringUtils.substring(publishDate, j, j + 2);
// 若为2月份,且日大于28日,则取2月的最后一天
if (month == 2 && Integer.parseInt(day) > 28)

...{
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(year), month - 1, 1);
day = String.valueOf(cal
.getActualMaximum(Calendar.DAY_OF_MONTH));
}
Date date = DateUtils.parseDate(yearAndMonthStr + day,
dateFormat);
set.add(date);
}
catch (ParseException e)

...{
e.printStackTrace();
}
}
}
return set;
}


/** */
/**
* 出版日期中的数字代表星期几

* 0-星期日、1-星期一、2-星期二、3-星期三、4-星期四、5-星期五、6-星期六
*
* @param year
* 年份
* @param publishWeek
* 出版日期
* @param weekStart
* 开始星期数
* @param weekInterval
* 间隔的星期数
* @return
*/
private
static
Set
<?>
digitsRepresentWeek(String year, String publishWeek,
int
weekStart,
int
weekInterval)

...
{
Set<Date> set = new TreeSet<Date>();
Calendar cal = Calendar.getInstance();
int yearNumber = Integer.parseInt(year) ;
for (int weekOfYear = weekStart; weekOfYear <= 53; weekOfYear += weekInterval)

...{
cal.set(Calendar.YEAR, yearNumber);// 设置年份
cal.set(Calendar.WEEK_OF_YEAR, weekOfYear);// 设置星期数
for (int i = 0 ;i < publishWeek.length() ;i++)

...{
int dayOfWeek = Integer.parseInt(StringUtils.substring(publishWeek, i, i+1)) +1 ;
cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);// 设置星期几
// 若计算出来的日期为该年度日期则设置到集合中
if (cal.get(Calendar.YEAR) == yearNumber)

...{
set.add(cal.getTime());
}
}
}
return set;
}
这三个为主要的处理函数,其他都通过调用这三个函数来进行处理,如双月刊,单月出版,则
int
[] months
=
{
1
,
3
,
5
,
7
,
9
,
11
};
return
digitsRepresentDay(year, publishDay, months);