一段时间周一次数

 1 import java.text.ParseException;
 2 import java.text.SimpleDateFormat;
 3 import java.util.Calendar;
 4 import java.util.Date;
 5 
 6 public class test1 {
 7     public static void main(String[] args) {
 8         System.out.println(method("2020-08-01", "2020-08-31"));
 9     }
10     public static int method(String startDate,String endDate){
11         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
12         Date date;
13         int count = 0; //星期一的次数
14         try{
15             while (true){
16                 date = format.parse(startDate);
17                 //将起始日期转为Date类型
18                 //开始日期的毫秒值
19                 if(date.getTime() <= format.parse(endDate).getTime()){
20                     //如果开始日期的毫秒值小于结束日期的毫秒值
21                     Calendar cal = Calendar.getInstance(); //获取指定的时间点
22                     cal.setTime(date); //设置起始时间的时间点
23                     if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.MONDAY){
24                         //如果是星期一, 次数+1
25                         count++;
26                     }
27                     //迭代一天
28                     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
29                     Date date2 = df.parse(startDate);
30                     startDate= df.format(new Date(date2.getTime()+ 24 * 60 * 60 * 1000));
31                 }else{
32                     break;
33                 }
34             }
35         }catch (ParseException e){
36             e.printStackTrace();
37         }
38         return count;
39     }
40 }

 

posted @ 2021-05-18 15:06  转角的遇见  阅读(66)  评论(0)    收藏  举报