flatpickr 土日・祝日対応

flatpickr でもやってみた。

  • 土日に色をつける
  • 祝日も色をつける
  • 土日祝は無効
  • 明日以降のみ有効

※jQuery使用

<input class="flatpickr">

<link rel="stylesheet" href="https://npmcdn.com/flatpickr/dist/flatpickr.min.css">
<style>
/* 土日祝の色(日曜はじまり) */
.flatpickr-weekday:nth-child(1) { color: rgba(255, 0, 0, 0.6); }
.flatpickr-weekday:nth-child(7) { color: rgba(0, 0, 255, 0.6); }
.flatpickr-day.saturday:not(.selected) { color: rgb(0, 0, 255); }
.flatpickr-day.prevMonthDay.saturday:not(.selected),
.flatpickr-day.nextMonthDay.saturday:not(.selected),
.flatpickr-day.flatpickr-disabled.saturday:not(.selected) { color: rgba(0, 0, 255, 0.2); }
.flatpickr-day.sunday:not(.selected),
.flatpickr-day.jp-holiday:not(.selected) { color: rgb(255, 0, 0); }
.flatpickr-day.prevMonthDay.sunday:not(.selected),
.flatpickr-day.nextMonthDay.sunday:not(.selected),
.flatpickr-day.prevMonthDay.jp-holiday:not(.selected),
.flatpickr-day.nextMonthDay.jp-holiday:not(.selected),
.flatpickr-day.flatpickr-disabled.sunday:not(.selected),
.flatpickr-day.flatpickr-disabled.jp-holiday:not(.selected) { color: rgba(255, 0, 0, 0.2); }
</style>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://npmcdn.com/flatpickr/dist/flatpickr.min.js"></script>
<script src="https://npmcdn.com/flatpickr/dist/l10n/ja.js"></script>
<script>
(function($){
    // 祝日取得
    $.get('https://holidays-jp.github.io/api/v1/date.json', function( holidays ){
        // 日本語ピッカー(日曜はじまり)
        flatpickr.l10ns.ja.firstDayOfWeek = 0;
        $(".flatpickr").flatpickr({
            locale: 'ja',
            disableMobile: true,
            // 出力書式
            dateFormat: 'Y年m月d日',
            // 日付毎カスタム処理
            onDayCreate: onDayCreate,
            // 明日から有効
            minDate: tomorrow()
        });
        // 日付毎に
        function onDayCreate( dObj, dStr, fp, dayElem ){
            // 土日無効・クラス付与
            var dayOfWeek = dayElem.dateObj.getDay();
            switch( dayOfWeek ){
                case 0: $(dayElem).addClass('flatpickr-disabled sunday'); break;
                case 6: $(dayElem).addClass('flatpickr-disabled saturday'); break;
            }
            // 祝日無効・クラス付与
            var ymd = YMD(dayElem.dateObj);
            if( ymd in holidays ) $(dayElem).addClass('flatpickr-disabled jp-holiday');
        }
        // 明日
        function tomorrow(){
            var d = new Date();
            d.setDate(d.getDate() + 1);
            return YMD(d);
        }
        // yyyy-mm-dd
        function YMD( d ){
            var Y = d.getFullYear();
            var M = d.getMonth() + 1;
            var D = d.getDate();
            return [Y, ('0' + M).slice(-2), ('0' + D).slice(-2)].join('-');
        }
    });
})(jQuery);
</script>

祝日データは Holidays JP API を利用しています。