'java'에 해당되는 글 1건

  1. 2018.02.23 날짜와 날짜 사이의 차이가 필요할때

날짜와 날짜 사이의 차이가 필요할때

|

날짜와 날짜 사이의 차이가 필요했다. 


예를들어 날짜-날짜 =  123일 차이입니다. 이런식의 예제는 많은데 내가 필요한건 month 차이가 몇이냐는 것.


그것도 서브스트링으로 month 만 취해서 계산하는 야매가 아니고 정확히 달력기준으로 구해야 한다는 것.


1월 5일과 2월 1은 한달 차이는 아니잖는가? 


출처 : https://stackoverflow.com/questions/27181307/how-to-find-number-of-months-between-two-date-range-in-java-using-calender-api


도움주신 안드로이드 개발자 단톡방 님들께 감사를.


static int monthsBetween(Date a, Date b) {
    Calendar cal = Calendar.getInstance();
    if (a.before(b)) {
        cal.setTime(a);
    } else {
        cal.setTime(b);
        b = a;
    }
    int c = 0;
    while (cal.getTime().before(b)) {
        cal.add(Calendar.MONTH, 1);
        c++;
    }
    return c - 1;
}


메소드 구현후


public static void main(String[] args) {
    String start = "01/01/2012";
    String end = "31/07/2014";
    DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    try {
        System.out.println(monthsBetween(sdf.parse(start), sdf.parse(end)));
    } catch (ParseException e) {
        e.printStackTrace();
    }
}


위 처럼 실행.

아래는 결과. 30개월 차이라는뜻.

30


위 코드중   Calendar.MONTH 부분을 잘 응용하면 일수나, 년수로도 값을 뽑아낼수있다.

And
prev | 1 | next