java 求取某一段时间内的每一天、每一月、每一年

时间:2021-05-14 07:55:52

1.求取某一段时间内的每一天

1     Date date0 = new SimpleDateFormat("yyyy-MM-dd").parse("2014-01-01");
2             Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse("2014-10-03");
3             Calendar cal = Calendar.getInstance();
4             cal.setTime(date0); 
5             while(cal.getTime().compareTo(date1)<=0){ 
6             cal.add(Calendar.DAY_OF_MONTH,1);
7              list0.add(sdf.format(cal.getTime()));
8             }

2.求取某一段时间内的每一月
方法一:

date0 = new SimpleDateFormat("yyyy/MM/dd").parse("2014/01/01");
            Date date1 = new SimpleDateFormat("yyyy/MM/dd").parse("2014/10/03");
            Calendar cal = Calendar.getInstance();
            cal.setTime(date0); 
            while(cal.getTime().compareTo(date1)<=0){ 
            cal.add(Calendar.DAY_OF_MONTH,1);
              list0.add(sdf.format(cal.getTime()));
            }

方法2:

 1 /**
 2              * 求取月分
 3              */
 4                 List<String> list01 = new ArrayList<String>();
 5                Date begin = sdf.parse("2014/01/01");   
 6                 Date end = sdf.parse("2014/10/03");  
 7                 Calendar cal1 = Calendar.getInstance();
 8                 cal1.setTime(begin); 
 9                 Calendar cal2 = Calendar.getInstance();
10                 cal2.setTime(end);
11                  int mouths = cal2.get(Calendar.MONDAY)- cal1.get(Calendar.MONTH);//获取年份
12                for (int i = 0; i <= mouths; i++) {   
13                     cal1.add(Calendar.MONTH,1);     
14                    list01.add(sdfq.format(cal1.getTime()).trim());   
15                }

3.求取每一年
方法一:

 1 //方法一
 2         date0 = new SimpleDateFormat("yyyy").parse("2010");
 3         Date date1 = new SimpleDateFormat("yyyy").parse("2014");
 4         Calendar cal = Calendar.getInstance();
 5         cal.setTime(date0); 
 6         while(cal.getTime().compareTo(date1)<=0){ 
 7         list0.add(sdf.format(cal.getTime()));
 8         cal.add(Calendar.YEAR,1);
 9           
10         }


方法二:

 1 Date begin = sdf.parse("2014");   
 2 //            Date end = sdf.parse("2014");  
 3 //            Calendar cal1 = Calendar.getInstance();
 4 //            cal1.setTime(begin); 
 5 //            Calendar cal2 = Calendar.getInstance();
 6 //            cal2.setTime(end);
 7 //             int mouths = cal2.get(Calendar.YEAR)- cal1.get(Calendar.YEAR);//获取年份
 8 //           for (int i = 0; i <= mouths; i++) { 
 9 //               if(i!=0){
10 //                   cal1.add(Calendar.YEAR,1); 
11 //               }
12 //               list02.add(sdfp.format(cal1.getTime()).trim());   
13 //           }