간만에 삽질 제대로 했다.

문제보고 마지막일에서 시작일을 빼고 그 기간만큼 돌려주지 하는 마음으로 시작했는데.. 헐

달은 12가 맥시멈인걸 깜빡.. 지대로 삽질해서 무려 한시간 가까이 걸려서 만들었다.

 

처음의 예상이 빗나가서 알고리즘을 전면 재수정 해서 생각을 하고 만들어야 하는데..

귀찮아서 적응하듯 만들면서 수정을 계속했더니

 

 

질문) 자바 두개의 날짜 사이에 월 구하기

 

자바 두개의 날짜 사이에 월 구하기

예)

s_date = '20160101';
e_date = '20170102';

출력 :
201601
201602
201603
.
.
.
201701

 

 

답변)

 

1. CLASS

 

public class test_0329_01 {
  public static void main(String[] args) {
  
    String sd = "20160131";
    String ed = "20190121";
  
    int[] s_date = new int[3];
    int[] e_date = new int[3];
  
    s_date[0] = Integer.parseInt(sd.substring(0, 4));
    s_date[1] = Integer.parseInt(sd.substring(4, 6));
    s_date[2] = Integer.parseInt(ed.substring(6));
  
    e_date[0] = Integer.parseInt(ed.substring(0, 4));
    e_date[1] = Integer.parseInt(ed.substring(4, 6));
    e_date[2] = Integer.parseInt(ed.substring(6));
  
    // System.out.println(s_date[0] + " / " + s_date[1] + " / " + s_date[2]);
    // System.out.println(e_date[0] + " / " + e_date[1] + " / " + e_date[2]);
  
    int tot = 0;
    int countM = 0;
    int countY = 0;

    countY = e_date[0] - s_date[0];
    countM = e_date[1] - s_date[1];
  
    if(countM <= 0){
      countY = countY - 1;
    }
  
    if(e_date[2] == 1){
      countM = 12 + countM;
    }else{
      countM = 12 + countM +1;
    }
  
    System.out.println("누적월 : " + ((countY * 12) + countM));
    System.out.println();


    tot = (countY * 12) + countM;
  
    /*  삽질부분.. 나쁘진 않지만.. 버그발생.. 그리고 for는 적게 쓸수록 좋으니까.. 위와같이 하면 간단.
    for(int i = s_date[0]; i <= e_date[0];i++){
   
      for(int j = s_date[1]; j < e_date[1];j++){
        if(0 < j && j <= 12 ){
          countM++;
        }else{
          break;
        }
      }
      countY++;
    }
    */

    int num = s_date[1];


    for(int k = 1;k <= tot;k++){
   
      if(num > 9){
        System.out.println(s_date[0] + "" + s_date[1]);
      }else if(num <= 9){
        System.out.println(s_date[0] + "0" + s_date[1]);
      }
   
      if(num == 12){
        s_date[0]++;
        num = 0;
        s_date[1] = 1;
      }else{
        s_date[1]++;
      }
      num++;
    }
  }
}

 

 

2. RUN

 

누적월 : 37

201601
201602
201603
201604
.

.

.
201806
201807
201808
201809
201810
201811
201812
201901