posted by 지긋이 2019. 12. 2. 15:12

생각보다 빈번하게 사용하는 거라 정리 한번.

1. 문자 -> 날짜(타입바꾸기)로 변경
calcu_formatChk(reqYmd);

function calcu_formatChk(ymd){ //형식이 yyyymmdd일 경우 . 만약 하이픈(-)이 포함되어 있다면 변환작업 후 진행(3번)
        var yyyy = ymd.substr(0,4); 
        var mm = ymd.substr(4,2); 
        var dd = ymd.substr(6,2);                         
         
      calcu_ymd = new Date(yyyy, mm-1, dd); 
       //console.log(ymd +"|결과 : " + calcu_ymd + "/n 월Chk : " + (calcu_ymd.getMonth()+1)); 
       return calcu_ymd; 
    }

2. 날짜 차이 구하기
getDayFromToCalDay(dt1, dt2);

function getDayFromToCalDay(dt1, dt2) { //Date 타입 혹은 YYYYMMDD로 들어왔을 때
        var diffDate_1 = dt1 instanceof Date ? dt1 :new Date(dt1);  //Test 필요(Date가 아닐 때 1번으로 연결하면 될 듯)
        var diffDate_2 = dt2 instanceof Date ? dt2 :new Date(dt2);  //Test 필요(Date가 아닐 때 1번으로 연결하면 될 듯)
                 
        var calDay = Math.abs(diffDate_2.getTime() - diffDate_1.getTime()); //시간으로 계산
        calDay = Math.ceil(calDay / (1000 * 3600 * 24)); //날짜로 변환
        //console.log(dt1+"|"+dt2+"\n날짜비교>>"+diffDate_1+"|"+diffDate_2+"||"+calDay); 
        return calDay
    }

3. 하이픈 포함된 날짜 하이픈 제거해서 반환
formatDate(searchApplYmd,"-");

// 날짜 포맷을 적용한다.. 
    function formatDate(strDate, saper) { 
        if(strDate == "" || strDate == null) { 
            return ""; 
        } 

        try { 
            if(strDate.length == 10) { //YYYY-MM-DD
                return strDate.substring(0,4)+saper+strDate.substring(5,7)+saper+strDate.substring(8,10); 
            } else if(strDate.length == 8) { 
                return strDate.substring(0,4)+saper+strDate.substring(4,6)+saper+strDate.substring(6,8); 
            } else { 
                return ""; 
            } 
        } catch(e) { 
            return ""; 
        } 
    }