public static void main(String args[]) throws Exception{
countDays("2013-02-1","2013-03-01");
loopCalendar ("2013-02-1","2013-02-05");
}
/**
* 计算两天的相差天数
* @param startDay
* @param endDay
* @throws Exception
*/
public static void countDays(String startDay , String endDay) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = sdf.parse(startDay);
Date d2 = sdf.parse(endDay);
System.out.println("相差:" + (getDays(d2) - getDays(d1)));
}
//获取天数
public static int getDays(Date d)
{
Calendar c = Calendar.getInstance();
c.setTime(d);
int dDay = c.get(Calendar.DATE);
int dYear = c.get(Calendar.YEAR);
int dMonth = c.get(Calendar.MONTH) + 1; //注意month是从0开始计的我们加1
int days=0;
int[] months={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(dYear%400==0||dYear%4==0&&dYear%100!=0){
months[2]=29;
}
days=(dYear-1)*365+(dYear-1)/4-(dYear-1)/100+(dYear-1)/400;
for(int i=1;i<dMonth;i++){
days+=months[i];
}
days+=dDay;
return days;
}
/**
* 循环开始到结束的天数
* @param startDay
* @param endDay
* @throws Exception
*/
public static void loopCalendar(String startDay , String endDay) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date fromDate = sdf.parse(startDay);
Date thruDate = sdf.parse(endDay);
Calendar c = Calendar.getInstance();
c.setTime(fromDate);
while(true){
Date f = c.getTime();
if(f.compareTo(thruDate)>0){
break;
}
int dDay = c.get(Calendar.DATE);
int dYear = c.get(Calendar.YEAR);
int dMonth = c.get(Calendar.MONTH) + 1;
System.out.println("年:"+dYear+",月:" +dMonth+",日:"+dDay+" "+sdf.format(f));
c.add(Calendar.DATE, 1);
}
}
输出结果:
相差:28
年:2013,月:2,日:1 2013-02-01
年:2013,月:2,日:2 2013-02-02
年:2013,月:2,日:3 2013-02-03
年:2013,月:2,日:4 2013-02-04
年:2013,月:2,日:5 2013-02-05
计算时间的两天的相差天数和循环天数
最新推荐文章于 2022-03-25 17:38:20 发布