Library/jQeury

jquery/Javascript DatePicker를 보고 만든 WeekPicker(3) - 마무리

청렴결백한 만능 재주꾼 2021. 6. 11. 22:59
반응형

최종 화면 완성/ 첫번째)WK이 있고 월요일 시작, 출력 form 이 다름./ 두번째)WK이 있고 월요일 시작 / 세번째)WK이 있고 일요일 시작..WK을 없앨수도 있다.

 

첫번째 게시글

 

jquery/Javascript DatePicker를 보고 만든 WeekPicker(1)

어느덧 흘러 흘러 jquery & HTML & css & javascript 까지 오게 되었다. 자 달력은 www.youtube.com/watch?v=FBO_7H39tqs 이거 개발자의 품격님의 유튜브와 Datepicker란 jquery의 내장 기능과 각종 인터넷을 참고..

guseowhtjs.tistory.com

2번째 게시글

 

jquery/Javascript DatePicker를 보고 만든 WeekPicker(2)

몇 일이 더 흘렀을까... 결국 흘러 흘러 여기까지 오게 되었다. UI적인 변화 음 만족스럽다. 여기저기 달력을 많이 참고하였다. 1. input창에 뜨는 출력값을 설정가능하다. 2. 오늘의 날짜가 노란색

guseowhtjs.tistory.com

 

약 두달여 간에 작업 끝에 완성한 Weekpicker. 날짜 date를 선택하는 달력은 있지만 week을 픽하는 달력이 필요하여 만들었다. 제이쿼리 jquery와 자바스크립트javascript를 이용하여 만들었으며 윤달, 윤력 계산이 다 되어 있으며 무조건 1월 1일이 있는 주가 1번째 주가 되도록 하였다.(이거는 기준을 어떻게 세우냐에 따라 다르다.) 아직까진 어딘가에서 문제가 없이 잘 작동하고 있다. 

 

기능

1. 요일의 표시형식 바꿀 수 있음.

2. 키보드로 자유자재로 이동 가능(포커스가 input창으로 되어 있을 때)

3. Set , Get 기능이 있는데 

3-1. SET은 코드로 지정해놓은 기본값으로 돌아가는 것이다. (기본값 양식 : yyyy-Www, 예 : 2021-W05 - 2021년도 5번째 주)

3-2  GET은 현재 지정해 놓은 Week을 가져오는 것이다.

4. 오늘 날짜는 노란색으로 표시가 된다.

5. 년과 월은 자유롭게 입력이 가능하다.

 

소스코드

'use strict';
let exWPs = [], exWPobject = [], exWPId = 0;

function exWeekPickerType(exWP) {
    let id = exWP.id;

    this.setWeekValue = function (val) {
        if (typeof (val) !== 'string') return;
        exWP.weekValue = val;

        $('#warper' + id).find('tbody tr:nth-child(' + getDateByWeek(id, exWP) + ')').addClass('clicked');
    };

    this.getWeekValue = function () {
        return (exWP.weekValue.length < 1 ? "null" : exWP.weekValue)
    }
}

function getDateByWeek(id, exWP) {
    let value = exWP.weekValue;
    let y = value.substring(0, 4);
    let w;
    if (value.length < 8)w = Number('0' + value.substring(6, 7))
    else w = Number(value.substring(6, 8))
    

    let first = new Date('01-01-' + y);

    let gap = w * 7 - first.getDay() - 1;

    let setted_date = first.addDays(gap);
    
    let m = setted_date.getMonth();
    let d = setted_date.getDate();

    let month = String(Number(m) + 1);
    
    if (month.length < 2) month = '0' + month;
    
    let firstDayMonth = new Date(month + '-01-' + y);
    let first_day = 0;
    
    if (exWP.firstDay) (firstDayMonth.getDay() == 0 ? first_day = 6 : first_day = firstDayMonth.getDay() - 1);
    else first_day = firstDayMonth.getDay();
    
    let nthwk = Math.floor((d + first_day -1) / 7) + 1;

    exWP.dateValue = d;
    exWP.nthWkValue = nthwk;
    exWP.yearValue = y;
    exWP.monthValue = m;
    $('#yearChange' + id).val(y);
    $('#monthChange' + id).val(m);

    changeYearMonth(y, m, id);
    getWeekNumber(nthwk, id);
    $('#warper' + id).find('tbody tr:nth-child(' + nthwk + ')').addClass('clicked');
    return nthwk;
}

//제이쿼리 함수
$.fn.Weekpicker = function (jsonConfig) {
    if (this.selector === undefined && this.length > 0 && this[0].id !== undefined && this[0].id !== null)
        this.selector = '#' + this[0].id;

    if (typeof (jsonConfig) === 'object') {
        let current_year = (new Date()).getFullYear();
        let current_month = (new Date()).getMonth();

        jsonConfig.selector = this.selector;
        jsonConfig.id = exWPId + 1;
        let inID = jsonConfig.id;

        $(this).addClass('ex-weekpicker ex-weekpicker-input ' + inID).attr('readonly', true).attr("onclick", "showWeekPicker(" + inID + ")").prop('title', jsonConfig.weekValue);

        exWPs.push(jsonConfig);

        $(this).parent().append(_htmlGenerate(inID));

        if (typeof jsonConfig.weekValue == 'string' &&
            jsonConfig.weekValue.length > 5) {
            getDateByWeek(inID, jsonConfig)
        } else {
            $(this).val("")
            $("#yearChange" + inID).val(current_year);
            $("#monthChange" + inID).val(current_month);
            jsonConfig.yearValue = current_year;
            jsonConfig.monthValue = current_month;
            changeYearMonth(current_year, current_month, inID);
        };

        // if (current_date < 7 &&
        //     $(this).next().find('#' + current_date).length == 2) $(this).next().find('tbody').find('tr:first').find('#' + current_date).parent().addClass('clicked');
        // else if (current_date > 22 &&
        //     $(this).next().find('#' + current_date).length == 2) $(this).next().find('tbody').find('tr:last').find('#' + current_date).parent().addClass('clicked');
        // else $(this).next().find('#' + current_date).parent().addClass('clicked');

        checkToday(inID);



        $('#prevButton' + inID).on('click', function (e) {
            checkToday(inID);
        });
        $('#nextButton' + inID).on('click', function (e) {
            checkToday(inID);
        });

        $("#tb_body" + inID).on('click', function (e) {
            if ($(e.target)[0]['localName'] == 'td') {
                let parent = $(e.target).parent();
                parent.addClass('clicked');
                jsonConfig.weekValue = parent.attr('title');
                if ($(e.target).parent().siblings('.clicked')) $(e.target).parent().siblings('.clicked').removeClass('clicked');
            };


            exCloseWeekPicker(inID)
            return;
        });
        
        //마우스휠 이벤트
        $("#ex-weekpicker-" + inID).on("mousewheel", function (e) {
            let E = e.originalEvent;
            let deltaY = E.wheelDelta;
            let direction = Math.round(deltaY / 120);

            y = Number($("#yearChange" + inID).val());
            m = Number($("#monthChange" + inID).val());
            if (direction > 0) {
                m = m + 1;
                if (m == 12) {
                    y = y + 1;
                    m = 0;
                };
            } else if (direction < 0) {
                m = m - 1;
                if (m === -1) {
                    y = y - 1;
                    m = 11;
                };
            }
            $("#yearChange" + inID).val(y);
            $('#monthChange' + inID).val(m);
            changeYearMonth(y, m, inID);
            checkToday(inID);
        })
        
        //키보드 방향키 이벤트
        $(this).keydown(function (e) {
            //ArrowLeft : 37, ArrowUp : 38, ArrowRight : 39, ArrowDown : 40
            let setted = $(e.target).next().find('.clicked');
            let weekName, target, clickedValue, nthValue, w;
            switch (e.key) {
                case "ArrowLeft":
                    weekName = setted.attr('name');
                    changeMonth(-1, inID);
                    checkToday(inID);

                    if (weekName) {
                        target = $(e.target).next();
                        if (target.find('tr[name="' + weekName + '"]').length != 0) target.find('tr[name="' + weekName + '"]').addClass('clicked');
                        else target.find('tbody').children(':last').addClass('clicked');
                    } else $(e.target).next().find('tbody').children(':first').addClass('clicked');

                    clickedValue = [];
                    clickedValue[3] = $(e.target).next().find('.clicked').attr('name');
                    clickedValue[2] = $(e.target).next().find('.clicked').children(':nth-child(5)').attr('id')
                    clickedValue[1] = Number($("#monthChange" + inID).val());
                    clickedValue[0] = Number($("#yearChange" + inID).val());
                    nthValue = Number(clickedValue[3].substring(0, 1));

                    getWeekNumber(nthValue, inID);
                    break;

                case "ArrowRight":
                    weekName = setted.attr('name')
                    changeMonth(1, inID);
                    checkToday(inID);

                    if (weekName) {
                        target = $(e.target).next();
                        if (target.find('tr[name="' + weekName + '"]').length != 0) target.find('tr[name="' + weekName + '"]').addClass('clicked');
                        else target.find('tbody').children(':last').addClass('clicked');
                    } else $(e.target).next().find('tbody').children(':first').addClass('clicked');

                    clickedValue = [];
                    clickedValue[3] = $(e.target).next().find('.clicked').attr('name');
                    clickedValue[2] = $(e.target).next().find('.clicked').children(':nth-child(5)').attr('id');
                    clickedValue[1] = Number($("#monthChange" + inID).val());
                    clickedValue[0] = Number($("#yearChange" + inID).val());
                    nthValue = Number(clickedValue[3].substring(0, 1));

                    getWeekNumber(nthValue, inID);
                    break;
                case "ArrowUp":
                    if (!setted) {
                        w = '4thweek' + inID;
                        $(e.target).next().find('tr[name=' + w + ']').addClass('clicked');
                        setted = $(e.target).next().find('.clicked');
                    };

                    if (setted.prev().length == 0) {
                        changeMonth(-1, inID);
                        checkToday(inID);

                        $(e.target).next().find('tbody').children(':last').addClass('clicked');

                    } else {
                        setted.prev().addClass('clicked');
                        setted.removeClass('clicked');
                    };

                    clickedValue = [];
                    clickedValue[3] = $(e.target).next().find('.clicked').attr('name');
                    clickedValue[2] = $(e.target).next().find('.clicked').children(':nth-child(5)').attr('id')
                    clickedValue[1] = Number($("#monthChange" + inID).val());
                    clickedValue[0] = Number($("#yearChange" + inID).val());
                    nthValue = Number(clickedValue[3].substring(0, 1));

                    getWeekNumber(nthValue, inID);

                    break;

                case "ArrowDown":
                    if (!setted) {
                        w = '1thweek' + inID;
                        $(e.target).next().find('tr[name=' + w + ']').addClass('clicked');
                        setted = $(e.target).next().find('.clicked');
                    };

                    if (setted.next().length == 0) {
                        changeMonth(1, inID);
                        checkToday(inID);
                        $(e.target).next().find('tbody').children(':first').addClass('clicked');
                    } else {
                        setted.next().addClass('clicked');
                        setted.removeClass('clicked');
                    };

                    clickedValue = [];
                    clickedValue[3] = $(e.target).next().find('.clicked').attr('name');
                    clickedValue[2] = $(e.target).next().find('.clicked').children(':nth-child(5)').attr('id')
                    clickedValue[1] = Number($("#monthChange" + inID).val());
                    clickedValue[0] = Number($("#yearChange" + inID).val());
                    nthValue = Number(clickedValue[3].substring(0, 1));

                    getWeekNumber(nthValue, inID);

                    break;

                case "Escape":
                    exAllCloseWeekPicker();
            }
        });
    } else if (jsonConfig === 'instance') {
        for (let i = 0; i < exWPs.length; i++) {
            if (exWPs[i].selector == this.selector) {
                let exWPType = new exWeekPickerType(exWPs[i]);
                return exWPType;
            }
        }
    };
}

function checkToday(id) {
    let y = Number($('#yearChange' + id).val());
    let m = Number($('#monthChange' + id).val());
    let cy = new Date().getFullYear();
    let cm = new Date().getMonth();
    let cd = String(new Date().getDate());

    if (y == cy &&
        m == cm) $('#tb_body' + id).find('#' + cd)['0'].classList.add('today');
    else if (y == cy &&
        m == cm - 1 &&
        $('#tb_body' + id).find('#' + cd).length == 2) $('#tb_body' + id).find('tr:last').find('#' + cd).addClass('today');
    else if (y == cy &&
        m == cm + 1 &&
        $('#tb_body' + id).find('#' + cd).length == 2) $('#tb_body' + id).find('tr:first').find('#' + cd).addClass('today');
};

function showWeekPicker(id) {
    $("#ex-weekpicker-" + id).toggle();
}

function getWeekNumber(nthWeek, id) {
    let exWP;
    for (let i = 0; i < exWPs.length; i++) {
        if (exWPs[i].id === id) {
            exWP = exWPs[i];
            break;
        }
    };

    let yearValue = $('#yearChange' + id).val();
    //let selectedFormat = $("#formatOption"+ id).val();
    let findInputElement = $("." + id);
    let weekDuration = formattingDate(nthWeek, id, yearValue);
    let startdate = new Date(weekDuration[0]);
    let enddate = new Date(weekDuration[1]);

    if (exWP.displayTemplate) {
        let displayText = exWP.displayTemplate(
            nthWeekOfYear(nthWeek, id),
            startdate,
            enddate);
        $(findInputElement).val(displayText);
    } else {
        $(findInputElement).val(yearValue + "-W" + nthWeekOfYear(nthWeek, id))
    };
}

function _htmlGenerate(id) {
    let exWP;
    for (let i = 0; i < exWPs.length; i++) {
        if (exWPs[i].id === id) {
            exWP = exWPs[i];
            break;
        }
    }

    let prevText = "Prev";
    let nextText = "Next";

    let dpDiv = $("<div/>", {
        id: "ex-weekpicker-" + id,
        style: 'display:none;z-index:9999;float:none;position:absolute;',
    }).addClass('ex-weekpicker ex-weekpicker-ui-weekpicker');

    let prev, monthOption, next, yearInput, selectFormat;

    prev = $('<button/>', {
        type: 'button',
        value: prevText,
        id: 'prevButton' + id,
        class: 'ex-weekpicker-controlButton-left',
    }).attr('onclick', 'changeMonth(-1,' + id + ')').append($('<i />', {
        class: 'fa fa-arrow-left',
    }));

    monthOption = $('<select />', {
        id: "monthChange" + id,
        class: "ex-weekpicker-form-controller ex-weekpicker-controlButton",
    }).attr('onchange', 'changeMonth(0,' + id + ')');

    next = $('<button/>', {
        type: "button",
        value: nextText,
        id: 'nextButton' + id,
        class: "ex-weekpicker-controlButton-right"
    }).attr('onclick', 'changeMonth(1,' + id + ')').append($('<i/>', {
        class: 'fa fa-arrow-right',
    }));

    yearInput = $('<input />', {
        type: "text",
        id: "yearChange" + id,
        class: "ex-weekpicker-yearchange"
    }).attr('onchange', 'changeYear(' + id + ')');

    let defaultMonthNames = {
        0: "JAN", 1: "FEB", 2: "MAR", 3: "APR", 4: "MAY", 5: "JUN",
        6: "JUL", 7: "AUG", 8: "SEP", 9: "OCT", 10: "NOV", 11: "DEC"
    };//default
    let monthNames = defaultMonthNames;

    if (exWP.monthNames) monthNames = exWP.monthNames;

    for (let i = 0; i < 12; i++) {
        monthOption.append("<option value=" + i + ">" + monthNames[i] + "</option>")
    };

    let format = $('<p>Format:</p>', {
        style: 'font-size:20px;'
    });

    let controlPanel = $('<div>', {
        id: "ex-weekpicker-controlpanel" + id,
        class: "ex-weekpicker-controlpanel",
    });

    format.append(selectFormat);
    controlPanel.append(yearInput);
    controlPanel.append(monthOption);
    controlPanel.append(prev);
    controlPanel.append(next);
    dpDiv.append(controlPanel)

    let weekDay = $('<table />', {
        class: "ex-weekpicker table-borderd"
    });

    let defaultDayNames = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]; //default

    let dayNames = defaultDayNames;
    let sunday = "";


    if (exWP.dayNames) { dayNames = exWP.dayNames };
    if (exWP.firstDay == 1) {
        sunday = dayNames.shift();
        dayNames.push(sunday);
    };

    let tableRow = $('<tr />', { id: "table-head-day", class: "ex-weekpicker" });
    let tableHead = $('<thead />', { class: "ex-weekpicker" });
    if (exWP.showWeek) {
        if (exWP.weekHeader) {
            $('<th>' + exWP.weekHeader + '</th>').appendTo(tableRow)
            for (let a = 0; a < dayNames.length; a++) {
                $('<th>' + dayNames[a] + '</th>').appendTo(tableRow)
            }
        } else {
            $('<th>#</th>').appendTo(tableRow)
            for (let a = 0; a < dayNames.length; a++) {
                $('<th>' + dayNames[a] + '</th>').appendTo(tableRow)
            }
        };
    } else {
        for (let a = 0; a < dayNames.length; a++) {
            $('<th>' + dayNames[a] + '</th>').appendTo(tableRow)
        }
    };

    tableHead.append(tableRow);
    weekDay.append(tableHead);
    weekDay.append($('<tbody />', { id: "tb_body" + id, class: "ex-weekpicker" }));

    dpDiv.append(weekDay);

    let warper = $('<div />', { id: "warper" + id, class: "ex-weekpicker" }).append(dpDiv);
    exWPId++;
    return warper;
}

function renderCalendar(data, id) {
    let exWP;
    for (let i = 0; i < exWPs.length; i++) {
        if (exWPs[i].id == id) {
            exWP = exWPs[i];
            break;
        }
    };
    let isShowWeek = exWP.showWeek;
    let year = exWP.yearValue;
    let month = (String(exWP.monthValue).length < 2 ? '0' + exWP.monthValue : exWP.monthValue);

    let h = [];
    for (let i = 0; i < data.length; i++) {
        let nthWeek = Math.floor(i / 7) + 1;
        if (i == 0) {
            if (isShowWeek == true) {
                h.push('<tr name="' + nthWeek + 'thweek' + id + '" onclick="getWeekNumber(' + nthWeek + ',' + id + ');" class="ex-weekpicker-weekSelect" title="' + year + '-' + 'W' + nthWeekOfYear(nthWeek, exWP.id) + '">');
                h.push('<td name="week" style="cursor:pointer;">' + nthWeekOfYear(nthWeek, id) + '</td>');
            } else {
                h.push('<tr name="' + nthWeek + 'thweek' + id + '" onclick="getWeekNumber(' + nthWeek + ',' + id + ');" class="ex-weekpicker-weekSelect" title="' + year + '-' + 'W' + nthWeekOfYear(nthWeek, exWP.id) + '">');
            }
        } else if (i % 7 == 0) {
            if (isShowWeek == true) {
                h.push('</tr>');
                h.push('<tr name="' + nthWeek + 'thweek' + id + '" onclick="getWeekNumber(' + nthWeek + ',' + id + ');" class="ex-weekpicker-weekSelect" title="' + year + '-' + 'W' + nthWeekOfYear(nthWeek, exWP.id) + '">');
                h.push('<td name="week" style="cursor:pointer;">' + nthWeekOfYear(nthWeek, id) + '</td>');
            } else {
                h.push('</tr>');
                h.push('<tr name="' + nthWeek + 'thweek' + id + '" onclick="getWeekNumber(' + nthWeek + ',' + id + ');" class="ex-weekpicker-weekSelect" title="' + year + '-' + 'W' + nthWeekOfYear(nthWeek, exWP.id) + '">');
            }
        }
        h.push('<td name="day" style="cursor:pointer;" id="' + data[i] + '">' + data[i] + '</td>');
    };
    h.push('</tr>');

    $('#tb_body' + id).html(h.join(""));
}

function changeYearMonth(year, month, id) {
    let exWP;
    for (let i = 0; i < exWPs.length; i++) {
        if (exWPs[i].id === id) {
            exWP = exWPs[i];
            break;
        }
    };
    exWP.yearValue = year;
    let month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    if (month == 1) {
        if (checkLeapYear(year)) month_day[1] = 29;
    }
    let first_day_of_week = getFirstDayOfWeek(year, month, exWP.firstDay);

    let arr_calendar = [];
    //전 달의 끝 날짜를 집어 넣는 작업
    for (let i = (month == 0 ? month_day[month_day.length - 1] : month_day[month - 1]) - first_day_of_week + 1; i <= (month == 0 ? month_day[month_day.length - 1] : month_day[month - 1]); i++) {
        arr_calendar.push(String(i));
    };

    for (let i = 1; i <= month_day[month]; i++) {
        arr_calendar.push(String(i));
    };

    let remain_day = 7 - (arr_calendar.length % 7);

    //이 달 끝에 다음 달의 앞 날짜를 당겨오는 작업
    if (remain_day < 7) {
        for (let i = 0; i < remain_day; i++) {
            arr_calendar.push(String(i + 1));
        }
    };

    renderCalendar(arr_calendar, id);
}

function checkLeapYear(year) {
    if (year % 400 == 0) {
        return true;
    } else if (year % 100 == 0) {
        return false;
    } else if (year % 4 == 0) {
        return true;
    } else {
        return false;
    }
}

function getFirstDayOfWeek(year, month, firstDay) {
    month += 1;
    if (month < 10) month = "0" + month;
    if (firstDay == 1) {
        if (Number((new Date(month + "-01-" + year)).getDay()) == 0) {
            return 6;
        } else {
            return (new Date(month + "-01-" + year)).getDay() - 1;
        }
    }

    return (new Date(month + "-01-" + year)).getDay();
}

function formattingDate(nth, id, yearValue) {
    let start = Number($('tr[name="' + String(nth) + 'thweek' + id + '"]').children("[name='day']:first").attr('id'))
    let end = Number($('tr[name="' + String(nth) + 'thweek' + id + '"]').children("[name='day']:last").attr('id'))
    let firstYear = Number(yearValue)
    let firstMonth = Number($('#monthChange' + id).val()) + 1
    let secondMonth = firstMonth
    let secondYear = firstYear
    if (firstMonth == 12) {
        if (nthWeekOfYear(nth, id) == 1 &&
            $('#monthChange' + id).val() == 11) {
            secondYear = firstYear + 1;
        }
    }

    if (start > end) {
        if (nth == 1) {
            firstMonth = firstMonth - 1;
            if (firstMonth == 0) {
                firstMonth = 12;
                firstYear = firstYear - 1;
            }
        } else if (nth >= 4) {
            secondMonth = secondMonth + 1;
            if (secondMonth > 12) { secondMonth = 1; }
        }
    }

    firstMonth = firstMonth.toString();
    secondMonth = secondMonth.toString();
    start = start.toString();
    end = end.toString();

    if (firstMonth.length < 2) { firstMonth = '0' + firstMonth };
    if (secondMonth.length < 2) { secondMonth = '0' + secondMonth };
    if (start.length < 2) { start = '0' + start };
    if (end.length < 2) { end = '0' + end };

    return [firstMonth + '/' + start + '/' + firstYear, secondMonth + '/' + end + '/' + secondYear]

}

function goToToday(id) {
    let current_year = (new Date()).getFullYear();
    let current_month = (new Date()).getMonth();
    $("#yearChange" + id).val(current_year);
    $('#monthChange' + id).val(current_month);
    changeYearMonth(current_year, current_month, id);
}

function changeMonth(diff, id) {
    let year, month;
    if (diff == 0) {
        year = Number($("#yearChange" + id).val());
        month = Number($("#monthChange" + id).val());
    } else {
        year = Number($("#yearChange" + id).val());
        month = Number($("#monthChange" + id).val());
        month = month + Number(diff);

        if (month == -1) {
            year = year - 1;
            month = 11;
        } else if (month == 12) {
            year = year + 1;
            month = 0;
        }
        if (year < 1 ||
            year > 9999) return;
    }

    loadCalendar(id, year, month);
}

function loadCalendar(id, y, m) {
    $("#yearChange" + id).val(y);
    $('#monthChange' + id).val(m);

    changeYearMonth(y, m, id);
}

function changeYear(id) {
    let year, month;
    year = Number($("#yearChange" + id).val());
    month = Number($("#monthChange" + id).val());
    if (year < 1 ||
        year > 9999) return;
    loadCalendar(id, year, month);
}

function nthWeekOfYear(nthWeek, id) {
    let year, month, exWP;
    for (let i = 0; i < exWPs.length; i++) {
        if (exWPs[i].id === id) {
            exWP = exWPs[i];
            break;
        }
    }
    year = $("#yearChange" + id).val();
    month = Number($("#monthChange" + id).val()) + 1;

    let first_day = new Date("01-" + (7 - (new Date("01-01-" + year).getDay()) + 1) + "-" + year);
    let first_of_month = new Date(month + "-01-" + year);
    let day_gap = (first_of_month - first_day) / 1000 / 60 / 60 / 24;
    let nthWeekOfThisYear = Math.ceil(((day_gap + 1) / 7) + nthWeek);

    if (nthWeekOfThisYear == 53) {
        if (checkLeapYear(year)) {
            if (exWP.firstDay == 0) {
                if (first_of_month.getDay() !== 4 &&
                    first_of_month.getDay() !== 5) nthWeekOfThisYear = 1;
            } else {
                if (first_of_month.getDay() !== 0 &&
                    first_of_month.getDay() !== 5) nthWeekOfThisYear = 1;
            }
        } else {
            if (exWP.firstDay == 0) {
                if (first_of_month.getDay() !== 4) nthWeekOfThisYear = 1;
            } else {
                if (first_of_month.getDay() !== 0) nthWeekOfThisYear = 1;
            }
        }
    } else if (nthWeekOfThisYear == 54) nthWeekOfThisYear = 1;


    return (String(nthWeekOfThisYear).length < 2 ? '0' + nthWeekOfThisYear : String(nthWeekOfThisYear));
}

function exAllCloseWeekPicker() {
    for (let x = 1; x <= exWPs.length; x++) {
        let allWeekPicker = $("#ex-weekpicker-" + x);
        allWeekPicker.hide();
    }
}

function exCloseWeekPicker(id) {
    $("#ex-weekpicker-" + id).hide();
}

$(document).ready(function () {
    $('body').on('click', function (e) {
        if ($(e.target).hasClass('ex-weekpicker') ||
            $(e.target).parent().hasClass('ex-weekpicker') ||
            $(e.target).parent().parent().hasClass('ex-weekpicker') ||
            $(e.target).parent().parent().parent().hasClass('ex-weekpicker') ||
            $(e.target).parent().parent().parent().parent().hasClass('ex-weekpicker') ||
            $(e.target).parent().parent().parent().parent().parent().hasClass('ex-weekpicker')) return;
        exAllCloseWeekPicker();
    });

});

 

//weekPicker.html

$("#date0").Weekpicker({
                firstDay: 0, //0 : sunday시작 , 1: monday 시작
                showWeek: true, // 몇 번째 주인지 나옴
                weekHeader: 'WK',
                weekValue: '2021-W35',
                //monthNames: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
                displayTemplate: function (weekName, firstDate, lastDate) {  //어떻게 표시할지 사용자가 지정 가능
                    let format = 'MM/dd'
                    startPoint = formatDate(firstDate, format)
                    endPoint = formatDate(lastDate, format)
                    nthWeek = (String(weekName).length < 2 ? '0' + String(weekName) : String(weekName))
                    year = ""
                    if (firstDate.getFullYear() == lastDate.getFullYear()) year = firstDate.getFullYear()
                    else if (firstDate.getFullYear() < lastDate.getFullYear()) {
                        if (lastDate.getMonth() == 0) year = lastDate.getFullYear()
                        else if (firstDate.getMonth() == 11) year = firstDate.getFullYear()
                    }
                    return year + "-W"+ nthWeek
                }
            })
            
function showValue1() {
            let wv = $('#date0').prop('title');
            let weekcal  = $('#date0').Weekpicker('instance');
            alert(weekcal.getWeekValue());
        }
        
function setValue1(val) {
            $('#date0').Weekpicker('instance').setWeekValue(val);
        }
반응형