很感谢论坛中的一位朋友给了我提示,后来想了下,是自己想的复杂了,在他的基础上整理了下如下代码:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package learn;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
*
* @author Administrator
*/
public class WeekCountOfQuarter {
public static void main(String[] args) throws ParseException {
String startTime = "2013-01-01";
String endTime = "2013-03-31";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
Calendar cs = Calendar.getInstance();
Calendar ce = Calendar.getInstance();
cs.setTime(startDate);
ce.setTime(endDate);
//获取年
int year = cs.get(Calendar.YEAR);
//季度第一个月的月份
int firstMonth = cs.get(Calendar.MONTH) + 1;
//季度最后一个月的月份
int lastMonth = ce.get(Calendar.MONTH) + 1;
//季度第一个月的天
int firstDay = cs.get(Calendar.DATE);
//季度最后一个月的天
int lastDay = ce.get(Calendar.DATE);
//季度第一个月的天所在星期是星期几
int firstDayOfWeek = cs.get(Calendar.DAY_OF_WEEK) - 1;
//第一天到所求那天的之间天数(仅限于一年中的两个时间段)
int dayCount = totalDay(year, firstMonth, firstDay, lastMonth, lastDay);
System.out.println(startTime + "到" + endTime + "总共有" + dayCount + "天");
//求结束时间在当前月份中是星期几
String week = DayOfWeek(firstDayOfWeek, dayCount); //求其实星期几
System.out.println(lastMonth + "月" + lastDay + "日,在这个季度中是星期" + week);
//第几个星期(第一个季度的最后一天所在的星期数就可以看做是一个季度的总共的星期数)
int totalWeek = weekCount(dayCount);
System.out.println(lastMonth + "月" + lastDay + "日,在这个季度中的第" + totalWeek + "个星期");
}
//计算在第几个星期
public static int weekCount(int ts) {
int zhengXingQi = ts / 7;
if (ts % 7 != 0) {
zhengXingQi += 1;
}
return zhengXingQi;
}
//计算这一天是星期几
public static String DayOfWeek(int firstDayOfWeek, int dayCount) {
int yuShu = dayCount % 7;
int xq = firstDayOfWeek + yuShu - 1;
String xingQi = "";
if (xq > 6) {
xq = xq % 7;
}
switch (xq) {
case 0:
xingQi = "日";
break;
case 1:
xingQi = "一";
break;
case 2:
xingQi = "二";
break;
case 3:
xingQi = "三";
break;
case 4:
xingQi = "四";
break;
case 5:
xingQi = "五";
break;
case 6:
xingQi = "六";
break;
}
return xingQi;
}
//获取两个时间段之间的天数
public static int totalDay(int year, int firstMonth, int firstDay, int lastMonth, int lastDay){
int yueShu = 0;
//firstMonth:起始月 lastMonth:结束月
for (int i = firstMonth; i < lastMonth; i++) {
yueShu += tianShu(year, i);
}
int ts = yueShu - firstDay + lastDay + 1;
return ts;
}
//返回这一年这个月的天数
public static int tianShu(int nian, int yue) {
if (yue == 2) {
if (shiFouRunNian(nian)) {
return 29;
} else {
return 28;
}
}
int ts = 0;
switch (yue) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
ts = 31;
break;
case 4:
case 6:
case 9:
case 11:
ts = 30;
break;
default:
}
return ts;
}
//判断是否为闰年
private static boolean shiFouRunNian(int nian) {
boolean run = false;
if (((nian % 4 == 0) && (nian % 100 != 0)) || (nian % 400 == 0)) {
run = true;
}
return run;
}
}