언어/JavaScript

[airdatepicker]데이트피커 주간으로 선택하기

홍시_코딩기록 2023. 8. 24. 21:11

데이트피커 주간으로 선택

<div class="">
    <input type="text" class="date_week" readonly>
    <span class="export_week"></span>
</div>
.date_week {
  width: 300px;
  cursor: pointer;
  padding: 10px;
  padding-left: 20px;
  border-radius: 20px;
  border: 0;
  outline: 0;
  color: #fff;
  font-size: 15px;
  background: #0cf;
  box-shadow: 0 4px 10px rgba(0,204,255, .3);
}

.date_week:hover {
  background: #26D4FF;
}

.date_week:active {
  background: #0bf;
  margin-top: 1px;
  box-shadow: 0 1px 10px rgba(0,204,255, .3);
}

.picker-icon {
  color: #fff;
  margin-left: -40px;
  pointer-events: none;
}

.datepicker--cell.-in-range- {
  background: rgba(90, 200, 240, .3);
}

.datepicker--cell.-focus- {
  background: rgba(0,120,180, .1);
}

.datepicker--cell-day.-other-month-, .datepicker--cell-year.-other-decade- {
  color: rgba(0,0,0, .25);
}

.row {
  pointer-events: none;
  position: absolute;
  width: 700%;
  height: 32px;
  left: 0;
  top: 0;
  border-radius: 6px;
  background: rgba(92,196,240, .2);
  /*left: -2px;
  top: -2px;
  border: 2px solid #5cc4ef;
  opacity: .5;*/
}
$('.date_week').datepicker({
              language: 'ko',
              autoClose: true,
              navTitles:{
                      days: '<span>yyyy</span>.</span><span>mm</span>', /* 일별 달력 타이틀 */
                      months: '<span>yyyy</span>', /* 월별 달력 타이틀 */
                      years: '<span>yyyy1</span>&nbsp;-</span>&nbsp;<span>yyyy2</span>' /* 년별 달력 타이틀 */
                  }, 
            })
            var cellCount=0, weekList=[];
            var row = createRowSelector();
            var rowDetect = false;
            
            var config = {
                // 주 모드
                week: {
                    inline: false,
                    autoClose: true,
                    toggleSelected: false,
                    language: "ko",
                    view: "days",
                    minView: "days",
                    dateFormat: "yyyy-mm-dd",
                        onRenderCell: function (date, cellType) {
                    var innerHtml = "";
                    var cellYear = date.getFullYear();
                    var cellMonth = date.getMonth();
                    var cellDate = date.getDate();
                    
                    $.each(weekList, function(i, k){
                        var y = parseInt(k.split("-")[0]);
                        var m = parseInt(k.split("-")[1])-1;
                        var d = parseInt(k.split("-")[2]);
                        
                        if (cellYear==y && cellMonth==m && cellDate==d) {
                        innerHtml = '<span class="active-week"></span>';
                        }
                    });
                    
                    if (cellType == "day") {
                        return { html: cellDate + innerHtml }
                    }
                    },
                    onShow: function (inst, animated) {
                    if (animated) rowDetect = true;
                    },
                    onHide: function (inst, animated) {
                    if (!animated) rowDetect = false;
                    },
                    onSelect: function (formattedDate, date, inst) {
                        var $exportWeek = $(".export_week");
                        var dateRangeText = getWeekByDateStr(formattedDate).join(" ~ ");
                        var combinedText = dateRangeText;
                        $exportWeek.html(combinedText);
                    }
                },
                
            };
            
            //주 모드 적용
            var $picker = $('.date_week');
                $picker.datepicker(config.week);
        
            /* 오늘 날짜 설정 */
            $picker.data('datepicker').selectDate(new Date());     
            
            /* 일주일 선택 이벤트 */
            weekSelector();
            function weekSelector () {
                $(".datepicker").mouseover(function(e){
                    if (!rowDetect) return;
                    if (typeof e.target.className!="string") return;
                    if (e.target.className.indexOf("datepicker--cell-day")==-1) return;
                    
                    var m = getSundayByDateStr(getDateStrByCell($(e.target)));
                    var currentRow = getCellByDateStr(m.format("YYYY-MM-DD"));
                    currentRow.appendChild(row);
                });
            }
            
            /* 일주일 선택 이벤트 */
            function createRowSelector () {
                var r = document.createElement("div");
                    r.setAttribute("class", "row");
                return r;
            }
            /* 해당 주의 일요일 계산 */
            function getSundayByDateStr (dateStr) {
                var sunday;
                var year = dateStr.split("-")[0];
                var month = dateStr.split("-")[1];
                var date = dateStr.split("-")[2];
                var day = new Date(year, month-1, date).getDay();
                var currentDate = moment([year, month, date].join("-"));
                
                if (day >= 0) {
                    sunday = currentDate.clone().subtract(day, 'days');
                }
                
                return sunday;
            }
            /* 문자열 생성 yyyy-mm-dd */
            function getDateStrByCell (cell) {
                var year = parseInt(cell.attr("data-year"));
                var month = parseInt(cell.attr("data-month"));
                var date = parseInt(cell.attr("data-date"));
                
                console.log(year);
                console.log(month);
                console.log(date);
                return [year, month+1, date].join("-");
            }
            
            
            /* 문자열 반환 */
            function getCellByDateStr (dateStr) {
                var cell;
                var yyyy = parseInt(dateStr.split("-")[0]);
                var mm = parseInt(dateStr.split("-")[1]);
                var dd = parseInt(dateStr.split("-")[2]);
                
                $.each($(".datepicker--cell-day"), function (i, k) {
                    if( k.dataset.year==yyyy && k.dataset.month==mm-1 && k.dataset.date==dd ) {
                    cell = k;
                    return true;
                    }
                });
                
                return cell;
            }
            /* 일 ~ 토 반환 */
            function getWeekByDateStr (dateStr) {
            var week=[];
            var m = getSundayByDateStr(dateStr);
            
                var sunday = m.format("YYYY.MM.DD");
                var Saturday = m.clone().add(6, "days").format("YYYY.MM.DD");
                
                week.push(sunday);
                week.push(Saturday);
            
            weekList = week;
            return week;
        }

주간 선택을 월 ~ 일로 바꾸려면 getWeekByDateStr과 getSundayByDateStr의 내용을 바꿔주면 된다.

 

 

* 혹시 사용하실 분 계시면 저는 air-datepicker 를 사용중이고 moment.js가 필요합니다!