計算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()); } } |