需求:计算任意一个时间段内的周末和周日的天数
* 思路:
* 1.获取时间段的天数
* 如果是同一年,直接获取: end_year(DAY_OF_YEAR) - begin_year(DAY_OF_YEAR)
*
* 如果时间段不是同一年,需要计算begin_year 的剩余天数,和end_year这一年的起始天数,
* 再计算end_year减去begin_year这几年的总天数
* 最后天数还要+1,因为两头都要遍历
*
* 2.进行遍历,假如某天为周末或周日,计数器就加1,每遍历一次就向后
* 加一天:c.add(Calendar.DAY_OF_MONTH,1);
*
不知道自己实现的方式是否有些复杂,是否有简单的方式,求高手指点- package cn.xushuai.io;
- import java.util.Calendar;
- class calendarDemo3{
- public static void main(String[] args){
-
- getDays();
- }
-
- public static void getDays(){
-
- Calendar c = Calendar.getInstance();
-
- int begin_year =2012;
- int begin_month =0;
- int begin_day =1;
-
- int end_year =2012;
- int end_month =11;
- int end_day =31;
-
-
-
- c.set(begin_year,begin_month,begin_day);
- //int begin_year = c.get(Calendar.YEAR);
-
- Calendar c2 = Calendar.getInstance();
- c2.set(end_year,end_month,end_day);
-
-
- //获取遍历次数
- int count = 0;
- if(end_year > begin_year){
- int years = end_year - begin_year ;
-
- //begin_year 的剩余天数
- int day = c.get(Calendar.DAY_OF_YEAR);
- c.set(begin_year, 11,31);
- int day2 = c.get(Calendar.DAY_OF_YEAR);
-
- int begin_year_days = day2-day;
- count = count +(begin_year_days);
-
- System.out.println(count);
-
- //end_year的天数
- int end_year_days =c2.get(Calendar.DAY_OF_YEAR);
-
- count+=end_year_days;
-
- //end_year减去begin_year的这几年的总天数
- for(int i=begin_year+1;i<years;i++){
-
- c.set(i,0,1);
- int year_days = c.get(Calendar.DAY_OF_YEAR);
- count = year_days+count;
-
- }
- }else if(begin_year == end_year){
-
- int beginday = c.get(Calendar.DAY_OF_YEAR);
- int endday = c2.get(Calendar.DAY_OF_YEAR);
-
- //begin_day和end_day,都要遍历,所以+1
- count+= (endday - beginday)+1;
- System.out.println(count);
-
- }else{
-
- System.out.println("请输入正确的日期格式 !");
- return;
- }
-
- int holiday = 0;
- c.set(begin_year,begin_month,begin_day);
- for(int i=0 ; i< count;i++){
-
- int weekday_flag = c.get(Calendar.DAY_OF_WEEK);
- if(weekday_flag ==1 || weekday_flag == 7){
- holiday++;
- }
- c.add(Calendar.DAY_OF_MONTH,1);
- }
- System.out.println("一共有:"+holiday+"天假期");
-
- }
- }
复制代码 |
|