2個日期間隔演算法,每隔多少個月後的第幾天

來源:互聯網
上載者:User

計算2個日期之間 每隔N個月後的第N天 得到所有的天數。

如下:private static String date1="2010-01-01";
private static String date2="2014-09-01";

2個日期之間每隔5個月的第5天輸出為:

2010-06-06
2010-11-11
2011-04-16
2011-09-21
2012-02-26
2012-07-31
2013-01-05
2013-06-10
2013-11-15

 

 

-------------------------------------------------------code------------------------------------------------

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateTemp {

private static String date1="2010-01-01";
private static String date2="2014-09-01";
private static String tempMoth="5";
private static String tempDay="5";
private static String FORMAT_DAY="yyyy-MM-dd";
public static void main(String [] args){
   SimpleDateFormat formt=new SimpleDateFormat("yyyy-MM-dd");
   try {
    int tempMothInt=Integer.parseInt(tempMoth);
    int tempDayInt=Integer.parseInt(tempDay);
    Date d1=formt.parse(date1);

    Date d2=formt.parse(date2);
    Calendar startCal = new GregorianCalendar();
         Calendar dealCal = new GregorianCalendar();
         startCal.setTime(d1);
         dealCal.setTime(d2);

//計算2個日期之間相差的月份 共多少個月
         int diffMonth = (dealCal.get(Calendar.YEAR) - startCal.get(Calendar.YEAR)) * 12 + dealCal.get(Calendar.MONTH) - startCal.get(Calendar.MONTH) + 1;

         String temp="";

//相差的月份除以每隔多少個月取整就是要迴圈的次數
         for(int i=0;i<diffMonth/tempMothInt;i++){
           
            if(i==0){

//得到相加月份和天數後的日期,如果是第一次迴圈傳入參數日期
               temp=getAfterMoth(d1,tempMothInt,tempDayInt);
               System.out.println(temp);
            }else{

//如果不是第一次迴圈則得到上一次相加後的日期當參數傳入得到相加月份和天數
              Date date=formt.parse(temp);
            temp=getAfterMoth(date,tempMothInt,tempDayInt);
        System.out.println(temp);
            }
            }
   } catch (ParseException e) {
    e.printStackTrace();
   }
  

}

//將一個日期相加月份和天數
public static String getAfterMoth(Date date,int moth,int days)
{
   SimpleDateFormat df = new SimpleDateFormat(FORMAT_DAY);
   Calendar calendar = Calendar.getInstance();  
   calendar.setTime(date);

//在月份上加moth個月
   calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH) +moth);

//在天數上加days個天。
   calendar.set(Calendar.DAY_OF_YEAR,calendar.get(Calendar.DAY_OF_YEAR) + days);
   return df.format(calendar.getTime());
}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.