`

java获取两日期的间隔天数

    博客分类:
  • java
阅读更多

这是我程序中用到的方法,传入的日期格式,可根据自己的需要作相应的改变。

/**
* 读取两个日期之间的天数
* @param begin  yyyy-mm-dd 
* @param end  yyyymmdd 
* @return
*/
public static int getDays(Date begin,String end) throws Exception{
		String strend=end.substring(0,4)+"-"+end.substring(4,6)+"-"+end.substring(6,8);
		int days=getBetweenDays(begin.toString(), strend); 
		return days;
	}
	
/** 
* 取得两个时间段的时间间隔 
* return t2 与t1的间隔天数 
* throws ParseException 如果输入的日期格式不是0000-00-00 格式抛出异常 
*/ 
public static int getBetweenDays(String t1,String t2) throws ParseException{ 
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		int betweenDays = 0; 
		Date d1 = format.parse(t1); 
		Date d2 = format.parse(t2); 
		Calendar c1 = Calendar.getInstance(); 
		Calendar c2 = Calendar.getInstance(); 
		c1.setTime(d1); 
		c2.setTime(d2); 
		// 保证第二个时间一定大于第一个时间 
		if(c1.after(c2)){ 
			c1 = c2; 
			c2.setTime(d1); 
		} 
		int betweenYears = c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR); 
		betweenDays = c2.get(Calendar.DAY_OF_YEAR)-c1.get(Calendar.DAY_OF_YEAR); 
		for(int i=0;i<betweenYears;i++){ 
			int tmp=countDays(c1.get(Calendar.YEAR));
			betweenDays+=countDays(c1.get(Calendar.YEAR));
			c1.set(Calendar.YEAR,(c1.get(Calendar.YEAR)+1)); 
		} 
		return betweenDays; 
	} 
	public static int countDays(int year){
		int n=0;
		for (int i = 1; i <= 12; i++) {  
            n += countDays(i,year);  
		}  
		return n;
	}
	

public static int countDays(int month, int year){  
        int count = -1;  
        switch(month){  
          case 1:  
          case 3:     
          case 5:  
          case 7:  
          case 8:  
          case 10:  
          case 12:  
            count = 31;  
            break;  
          case 4:  
          case 6:  
          case 9:  
          case 11:  
              count = 30;  
              break;  
          case 2:  
              if(year % 4 == 0)  
                  count = 29;  
              else  
                  count = 28;  
              if((year % 100 ==0) & (year % 400 != 0))  
                      count = 28;  
        }  
        return count;  
    }  

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics