java代码获得周六或者周日的个数
/**
* 查询日期间有几天一周中的某一天
* 日期格式 yyyy-MM-dd yyyy-MM-dd 1-7(表示周一到周日)
* @param startDate 准备查询的起始日期
* @param endDate 准备查询的结束日期
* @param dayOfWeek 准备查的一周中的某一天(准备查周几?)
* @return 包含所查周几的天数
* @throws ParseException 不支持跨年查询、不支持结束日期早于起始日期、周几输入错误等
*/
public static int getMondayNumber(Date startDate,Date endDate,int dayOfWeek) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int differenceDay = 0;
//实例化起始和结束Calendar对象
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
//分别设置Calendar对象的时间
startCalendar.setTime(startDate);
endCalendar.setTime(endDate);
//定义起始日期和结束日期分别属于第几周
int startWeek = startCalendar.get(Calendar.WEEK_OF_YEAR);
int endWeek = endCalendar.get(Calendar.WEEK_OF_YEAR);
//拿到起始日期是星期几
int startDayOfWeek = startCalendar.get(Calendar.DAY_OF_WEEK);
if(startDayOfWeek == 1) {
startDayOfWeek = 7;
startWeek--;
}else startDayOfWeek--;
//拿到结束日期是星期几
int endDayOfWeek = endCalendar.get(Calendar.DAY_OF_WEEK);
if(endDayOfWeek == 1) {
endDayOfWeek = 7;
endWeek--;
}else endDayOfWeek--;
//计算相差的周数
int differenceWeek = endWeek - startWeek;
//开始计算
if(startDayOfWeek <= dayOfWeek) {
if(endDayOfWeek >= dayOfWeek)
differenceDay = differenceWeek + 1;
}else if(startDayOfWeek > dayOfWeek) {
if(endDayOfWeek < dayOfWeek)
differenceDay = differenceWeek-1;
}else {
differenceDay = differenceWeek;
}
return differenceDay;
}