자바 비교 두 시간 차이 며칠, 몇 개 월, 몇 년

2354 단어 자바

 /**  
	      * @param date1             (null),          , :2009-09-12 
	      * @param date2           (null)        
	      * @param stype         0    ,1     ,2      
	      * @return  
	      *   :
	      * compareDate("2009-09-12", null, 0);//   
	      * compareDate("2009-09-12", null, 1);//   
	      * compareDate("2009-09-12", null, 2);//   
	      */ 
     public static int compareDate(String startDay,String endDay,int stype){  
         int n = 0;  
         String[] u = {" "," "," "};  
         String formatStyle = stype==1?"yyyy-MM":"yyyy-MM-dd";  
           
         endDay = endDay==null?getCurrentDate("yyyy-MM-dd"):endDay;  
           
         DateFormat df = new SimpleDateFormat(formatStyle);  
         Calendar c1 = Calendar.getInstance();  
         Calendar c2 = Calendar.getInstance();  
         try {  
             c1.setTime(df.parse(startDay));  
             c2.setTime(df.parse(endDay));  
         } catch (Exception e3) {  
             System.out.println("wrong occured");  
         }  
         //List list = new ArrayList();  
         while (!c1.after(c2)) {                   //     ,    ,n          
             //list.add(df.format(c1.getTime()));    //                       
             n++;  
             if(stype==1){  
                 c1.add(Calendar.MONTH, 1);          //     ,  +1  
             }  
             else{  
                 c1.add(Calendar.DATE, 1);           //     ,  +1  
             }  
         }  
         n = n-1;  
         if(stype==2){  
             n = (int)n/365;  
         }     
         System.out.println(startDay+" -- "+endDay+"     "+u[stype]+":"+n);        
         return n;  
     }   

public static String getCurrentDate(String format){
		Calendar day=Calendar.getInstance(); 
		day.add(Calendar.DATE,0); 
		SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd"
		String date = sdf.format(day.getTime());
		return date;
	}

좋은 웹페이지 즐겨찾기