java运用Calendar循环增加一个月获取响应的时间

public static void main(String[] args) {                   

             Calendar theCa = new GregorianCalendar();

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date d=format.parse("2017-12-27 11:44:50");

           theCa.setTime(d);

           SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");

           String currentDate=dft.format(theCa.getTime());

          Calendar calendar = Calendar.getInstance();

          calendar.setTime(theCa.getTime());

         calendar.set(Calendar.DAY_OF_MONTH,        calendar.getActualMaximum(Calendar.DAY_OF_MONTH));

        String maxDate=dft.format(calendar.getTime());

for(int i=1;i<=6;i++){

        if(maxDate.equals(currentDate)){//如果是最后一天,则需要是每个月的最后一天

                 theCa.add(Calendar.MONTH, 1);

                  Date   lastDate   =   theCa.getTime();  //只有在getTime之后,新增的时间才有效,所以先获取一下在设置

                 int   lastDay   =   theCa.getActualMaximum(Calendar.DAY_OF_MONTH);  

                theCa.set(Calendar.DATE, lastDay);

        }else{

                  theCa.add(Calendar.MONTH, 1);

                  if(theCa.get(Calendar.MONTH)>1){//在2月之后

                       Calendar cd=Calendar.getInstance();

                       cd.setTime(d);

                        int dateT=cd.get(Calendar.DATE);

                          theCa.set(Calendar.DATE, dateT);

                    }

        }

                 System.out.println(format.format(theCa.getTime()));

       }

}

猜你喜欢

转载自wangshupei123-163-com.iteye.com/blog/2407323