[ Web 관련 ]/자바스크립트

날짜 형식 변경, 오늘날짜, 어제날짜, 최근 7일, 최근 30일, 지난 주, 지난 달

BIZLAB 2021. 2. 16. 11:52
<script>

    //날짜 형식 변경 0000-00-00
    function formatDate(date) {
        let d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear();
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
        return [year, month, day].join('-');
    }

    function date_set(term){
        let date = new Date();
        let sdate, edate;
        let firstDayOfMonth

        if(term=='today'){
            //오늘날짜
            sdate = date;
            edate = date;
        }else if(term=='yesterday'){
            //어제날짜
            sdate = date.getTime() - (1 * 24 * 60 * 60 * 1000);
            edate = date.getTime() - (1 * 24 * 60 * 60 * 1000);
        }else if(term=='7'){
            //최근 7일
            sdate = date.getTime() - (7 * 24 * 60 * 60 * 1000);
            edate = date;
        }else if(term=='30'){
            //최근 30일
            sdate = date.getTime() - (30 * 24 * 60 * 60 * 1000);
            edate = date;
        }else if(term=='lastweek'){
            //지난 주
            sdate = new Date().setDate(date.getDate()-date.getDay()-7);
            edate = new Date().setDate(date.getDate()-date.getDay()-1);
        }else if(term=='lastmonth'){
            //지난 달
            firstDayOfMonth = new Date(date.getFullYear(), date.getMonth() , 1);
            edate = new Date(firstDayOfMonth.setDate(firstDayOfMonth.getDate() - 1));
            sdate = new Date(edate.getFullYear(), edate.getMonth(), 1);
        }

        $('input[name="sdate"]').val(formatDate(sdate));
        $('input[name="edate"]').val(formatDate(edate));
    }
</script>