计算时间的两天的相差天数和循环天数

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值