본문 바로가기

Programming/과거포스팅

자바 날짜 차이 구하기

출처 : http://blog.naver.com/uksuro?Redirect=Log&logNo=80085481551


여기서 퍼온 소스 제가 사용하는 양식에 맞게 수정했습니다. 함수로 이용가능하게요~


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


public class TimeTest {
    
    public static void main(String [] args)    {
        
        System.out.println(getDayDifference("20121031","20121108"));
    
    }
    
    //startDate,endDate ex)20121101
    public static int getDayDifference(String startDate, String endDate)    {
        
        startDate = startDate+"000000";
        endDate = endDate+"000000";
        
        long diffMillis = 0l;
        int diff = 0;
        
        try    {
            
            Date endDay = new SimpleDateFormat("yyyyMMddHHmmss").parse(endDate);
            Calendar endDayCal = new GregorianCalendar();
            endDayCal.setTime(endDay);
         
            Date startDay = new SimpleDateFormat("yyyyMMddHHmmss").parse(startDate);
            Calendar startDayCal = new GregorianCalendar();
            startDayCal.setTime(startDay);
             
            diffMillis = endDayCal.getTimeInMillis() - startDayCal.getTimeInMillis();
            
            diff = (int) (diffMillis/ (24 * 60 * 60 * 1000));
        }catch(ParseException e)    {
            e.printStackTrace(System.out);
        }
        
        return diff;
    }
}