Bootstrap datepicker:选择整周并在输入字段中输入周间隔

时间:2015-02-25 08:00:02

标签: jquery bootstrap-datepicker

我目前正在使用bootstrap-datepicker(https://github.com/eternicode/bootstrap-datepicker),但希望能够在日历中选择整周(星期一到星期日),并在输入字段中显示我的周间隔。选择。 输入字段中的默认间隔应该是您当前所在的周。

我见过一种类似的方法,使用jQuery UI在jsfiddle上显示间隔。

C

我已经尝试编辑此代码以使用bootstrap-datepicker,没有任何运气。

知道如何为bootstrap-datepicker实现这个功能吗? : The steps are outlined in this image

非常感谢任何帮助!

6 个答案:

答案 0 :(得分:34)

我在我的项目中使用了Bootstrap日期时间选择器遇到了与你相同的问题当试图选择周时。

我自己可以尝试下面的解决方案。

必填文件:

  1. Bootstrap.css
  2. Bootstrapdatetime picker css(您只能使用datepicker而不是datetime)
  3. 的jquery.js
  4. Bootstrap.js
  5. moment.js
  6. 引导日期时间选择器js(再次,您只能使用datepicker而不是datetime)
  7. HTML:

    <div class="container">    
        <div class="row">
            <div class="col-sm-6 form-group">
                <div class="input-group" id="DateDemo">
                  <input type='text' id='weeklyDatePicker' placeholder="Select Week" />
                </div>
            </div>
        </div>
    </div>
    

    JS:使用moment.js计算一周的开始和结束。

    //Initialize the datePicker(I have taken format as mm-dd-yyyy, you can have your own)
    $("#weeklyDatePicker").datetimepicker({
        format: 'MM-DD-YYYY'
    });
    
    //Get the value of Start and End of Week
    $('#weeklyDatePicker').on('dp.change', function (e) {
        value = $("#weeklyDatePicker").val();
        firstDate = moment(value, "MM-DD-YYYY").day(0).format("MM-DD-YYYY");
        lastDate =  moment(value, "MM-DD-YYYY").day(6).format("MM-DD-YYYY");
        $("#weeklyDatePicker").val(firstDate + "   -   " + lastDate);
    });
    

    CSS:

    .bootstrap-datetimepicker-widget tr:hover {
        background-color: #808080;
    }
    

    JSFiddle中的工作代码链接:

    https://jsfiddle.net/Prakash_Thete/9usq3enn/

答案 1 :(得分:9)

I have optimized the above mentioned examples.

HTML

<div class="container">    
   <div class="row">
       <div class="col-sm-6 form-group">
           <div class="input-group" id="DateDemo">
               <input type='text' id='weeklyDatePicker' placeholder="Select Week" />
           </div>
       </div>
   </div>
</div>

JS

$(document).ready(function(){
    moment.locale('en', {
      week: { dow: 1 } // Monday is the first day of the week
    });

  //Initialize the datePicker(I have taken format as mm-dd-yyyy, you can     //have your owh)
  $("#weeklyDatePicker").datetimepicker({
      format: 'MM-DD-YYYY'
  });

   //Get the value of Start and End of Week
  $('#weeklyDatePicker').on('dp.change', function (e) {
      var value = $("#weeklyDatePicker").val();
      var firstDate = moment(value, "MM-DD-YYYY").day(0).format("MM-DD-YYYY");
      var lastDate =  moment(value, "MM-DD-YYYY").day(6).format("MM-DD-YYYY");
      $("#weeklyDatePicker").val(firstDate + " - " + lastDate);
  });
});

CSS

.bootstrap-datetimepicker-widget .datepicker-days table tbody tr:hover {
    background-color: #eee;
}

Check the link for demo: https://jsfiddle.net/IamMHussain/ozdrdbqf/1/

答案 2 :(得分:3)

我目前正在开发一个具有相同要求的项目。不知道我在哪里找到它,但http://codepen.io/chanduvkm/pen/yeXKGW上的这个小提琴以稍微不同的方式解决了几乎相同的问题,但使用了您当前使用的bootstrap-datepicker库。可以轻松添加默认值。但是,当设置选项'weekStart:1'时,活动周的CSS失败,这是我实际需要的(周一开始ISO-8601周)。

    var startDate,
    endDate;

  $('#weekpicker').datepicker({
    autoclose: true,
    format :'mm/dd/yyyy',
    forceParse :false
}).on("changeDate", function(e) {
    //console.log(e.date);
    var date = e.date;
    startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
    endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay()+6);
    //$('#weekpicker').datepicker("setDate", startDate);
    $('#weekpicker').datepicker('update', startDate);
    $('#weekpicker').val((startDate.getMonth() + 1) + '/' + startDate.getDate() + '/' +  startDate.getFullYear() + ' - ' + (endDate.getMonth() + 1) + '/' + endDate.getDate() + '/' +  endDate.getFullYear());
});

在回应prakash之前的回答时,我将小提琴分到周一开始:https://jsfiddle.net/skfw0k53/添加以下内容:

    moment.locale('en', {
  week: { dow: 1 } // Monday is the first day of the week
});

所以,基本上两个不同的库来解决这个问题。

答案 3 :(得分:0)

你可以尝试一下。

必填文件:

的jquery-1.11.3.js
自举datepicker.min.js
自举datepicker.css
bootstrap.min.css

<强> HTML

<div class="container">
  <div class="row">
      <div class='col-md-3'>
    Week Start <select id="cweek">
      <option value='0'> 0 </option>
      <option value='1'> 1 </option>
      <option value='2'> 2 </option>
      <option value='3'> 3 </option>
      <option value='4'> 4 </option>
      <option value='5'> 5 </option>
      <option value='6'> 6 </option>
      <option value='7'> 7 </option>
    </select>
  </div>
  <div class='col-md-3'>
    Copy <select name='cweek_number' id='cweek_number'>
      <option value='1'> 1 Week </option>
      <option value='2'> 2 Week </option>
      <option value='3'> 3 Week </option>
      <option value='4'> 4 Week </option>
    </select> from
  </div>
</div>
</div>
<div class="container">
  <div class="row">


      <div class="from_cal"></div>
      </div>
      <div class="row">



      <div class="to_cal"></div>
    </div>
  </div>
</div>

<强> JS

var weekOfStart = 0;
      var startDate;
      var endDate;
      var toCal_startDate;
      var toCal_endDate;
      var setNumberOfWeek = 1;

      var from_cal = '.from_cal';
      var to_cal = '.to_cal';

      var obj =   $(from_cal).datepicker({
                  weekStart:weekOfStart,
                  maxViewMode: 0,
                  onSelect: function (date) {

                  },
                  beforeShowDay: function(date)
                  {
                    var cssClass = '';
                      if(date >= startDate && date <= endDate)
                          cssClass = 'oui-state-hover';
                      return [true, cssClass];
                  }
              //    startDate: new Date()
        });


      $(from_cal).on('changeDate', function(evt) {
          var date = evt.date;
          var dayAdjustment = date.getDay() - weekOfStart;
          if (dayAdjustment < 0) {
              dayAdjustment += 7;
          }
          if(setNumberOfWeek > 1)
          {
            weekLast = 7*(setNumberOfWeek-1);
          }
          else {
            weekLast = 0;
          }
          startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment);
          endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment + (6+weekLast));

          // console.log(startDate);
          // console.log(endDate);

          $(this).find('.active').closest('tr').addClass('oui-selected');
          if(setNumberOfWeek > 1)
          {
            $(this).find('.active').closest('tr').nextAll().slice(0, (setNumberOfWeek-1)).addClass('oui-selected');
          }
      });

        $(from_cal).on('mousemove', '.table-condensed tr', function () {
            $(this).find('td').addClass('oui-state-hover');
            if(setNumberOfWeek > 1)
            {

            $(this).nextAll().slice(0, (setNumberOfWeek-1)).find('td').addClass('oui-state-hover');
            }

        });
        $(from_cal).on('mouseleave', '.table-condensed tr', function () {

              $(this).find('td').removeClass('oui-state-hover');

              $(this).nextAll().find('td').removeClass('oui-state-hover');

        });


        $(from_cal).find('td').on('click', function(){

          console.log('ok');
        });

    obj.datepicker();


// To date Calendar  code

        var toCalObj =   $(to_cal).datepicker({
                      weekStart:weekOfStart,
                      maxViewMode: 0,
                  //    startDate: new Date()
        });
        toCalObj.datepicker();
        $(to_cal).on('mousemove', '.table-condensed tr', function () {
            $(this).find('td').addClass('kui-state-hover');
            if(setNumberOfWeek > 1)
            {

            $(this).nextAll().slice(0, (setNumberOfWeek-1)).find('td').addClass('kui-state-hover');
            }

        });
        $(to_cal).on('mouseleave', '.table-condensed tr', function () {

              $(this).find('td').removeClass('kui-state-hover');

              $(this).nextAll().find('td').removeClass('kui-state-hover');

        });

        $(to_cal).on('changeDate', function(evt) {

            var date = evt.date;
            var dayAdjustment = date.getDay() - weekOfStart;
            if (dayAdjustment < 0) {
                dayAdjustment += 7;
            }
            if(setNumberOfWeek > 1)
            {
              weekLast = 7*(setNumberOfWeek-1);
            }
            else {
              weekLast = 0;
            }
            toCal_startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment);
            toCal_endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment + (6+weekLast));

            console.log(toCal_startDate);
            console.log(toCal_endDate);

            $(this).find('.active').closest('tr').addClass('oui-selected');
            if(setNumberOfWeek > 1)
            {
              $(this).find('.active').closest('tr').nextAll().slice(0, (setNumberOfWeek-1)).addClass('oui-selected');
            }

          //  console.log(date.getDay());
        });


//comman code

      $('#cweek').change(function()
    {
      weekOfStart =  $('#cweek').val();
      obj.datepicker('destroy');
      toCalObj.datepicker('destroy');
      obj.datepicker({weekStart:$('#cweek').val(),maxViewMode:0}).datepicker('update');
      toCalObj.datepicker({weekStart:$('#cweek').val(),maxViewMode:0}).datepicker('update');
    });

    $('#cweek_number').change(function()
    {
      setNumberOfWeek = $('#cweek_number').val();
      obj.datepicker('destroy');
      toCalObj.datepicker('destroy');
      obj.datepicker({weekStart:$('#cweek').val(),maxViewMode:0}).datepicker('update');
      toCalObj.datepicker({weekStart:$('#cweek').val(),maxViewMode:0}).datepicker('update');

    });


    $('.table-condensed').addClass('table');

屏幕截图

enter image description here

JSFiddle链接https://jsfiddle.net/shivamanhar/ddphp8jx/9/

答案 4 :(得分:0)

如果有人改用daterangepicker 请按照扩展名进行选择,以选择星期

//moment.locale('ru') //depending on locale you can move start of week

set_picker_start_end = (picker, when) => {
  
  let m = (when == 'now') ? moment() : moment(when) //moment

  let week_start  = m.startOf('isoweek')
  let week_end    = m.clone().endOf('isoweek')
  
  picker.setStartDate(week_start);
  picker.setEndDate(week_end);
}

$("#week-dp").daterangepicker({
  // "showDropdowns": true,
  "showISOWeekNumbers": true,
  "autoApply": true,
  "showCustomRangeLabel": false,
  // "startDate": '', //not work because of one calendar. will be set further
  // "endDate": '', //not work because of one calendar. will be set further
  "drops": "down",
  "singleDatePicker" : true, //to make one click and one calendar
  "locale": {
    "format": "W [week of] GGGG",
    "weekLabel": "#",
  },
});

set_picker_start_end($("#week-dp").data('daterangepicker'), 'now') //set current week selected

$("#week-dp").on('show.daterangepicker', function(ev, picker) {

  let active_cell = picker.container[0].querySelector('td.start-date')
  active_cell.parentElement.classList.add('active') //tr goes active
});

$("#week-dp").on('apply.daterangepicker', function(ev, picker) {

    set_picker_start_end(picker, picker.startDate)
});

https://jsfiddle.net/dj_floyd/f2hoygdw/

答案 5 :(得分:-2)

一个非常快速的解决方案: 1.修改JS文件:bootstrap-datepicker.js 2.修改CSS文件:bootstrap-datepicker3.css 3.修改你的代码。

&#13;
&#13;
        //Modifications on bootstrap-datepicker.js
        //-----
        if (!target.hasClass('disabled')){
                // Clicked on a day
                if (target.hasClass('day')){
                        day = parseInt(target.text(), 10) || 1;
                        year = this.viewDate.getUTCFullYear();
                        month = this.viewDate.getUTCMonth();
                        //HF[+][i]201612151500
                        datepickerPlugin.actualWeek = $(target[0].parentNode).find('.cw').text();
                        //HF[+][f]201612151500
                        // From last month
                        if (target.hasClass('old')){
                                if (month === 0) {
                                        month = 11;
                                        year = year - 1;
                                        monthChanged = true;
                                        yearChanged = true;
                                } else {
                                        month = month - 1;
                                        monthChanged = true;
                                }
                        }
        //-----
        //HF[-][i]201612151500
        //   validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
        //HF[-][f]201612151500
        //HF[+][i]201612151500
        validParts: /ww?|dd?|DD?|mm?|MM?|yy(?:yy)?/g,
        //HF[+][f]201612151500
        nonpunctuation: /[^ -\/:-@\u5e74\u6708\u65e5\[-`{-~\t\n\r]+/g,
        parseFormat: function(format){
                if (typeof format.toValue === 'function' && typeof format.toDisplay === 'function')
                        return format;
                // IE treats \0 as a string end in inputs (truncating the value),
                // so it's a bad format delimiter, anyway
                var separators = format.replace(this.validParts, '\0').split('\0'),
                        parts = format.match(this.validParts);
                if (!separators || !separators.length || !parts || parts.length === 0){
                        throw new Error("Invalid date format.");
                }
                return {separators: separators, parts: parts};
        },
        //-----
        formatDate: function(date, format, language){
                if (!date)
                        return '';
                if (typeof format === 'string')
                        format = DPGlobal.parseFormat(format);
                if (format.toDisplay)
                        return format.toDisplay(date, format, language);
                var val = {
                        //HF[+][i]201612151500
                        ww: 'Semana ' + datepickerPlugin.actualWeek.toString(),
                        //HF[+][f]201612151500
                        d: date.getUTCDate(),
                        D: dates[language].daysShort[date.getUTCDay()],
                        DD: dates[language].days[date.getUTCDay()],
                        m: date.getUTCMonth() + 1,
                        M: dates[language].monthsShort[date.getUTCMonth()],
                        MM: dates[language].months[date.getUTCMonth()],
                        yy: date.getUTCFullYear().toString().substring(2),
                        yyyy: date.getUTCFullYear()
                };
                val.dd = (val.d < 10 ? '0' : '') + val.d;
                val.mm = (val.m < 10 ? '0' : '') + val.m;
                date = [];
                var seps = $.extend([], format.separators);
                for (var i=0, cnt = format.parts.length; i <= cnt; i++){
                        if (seps.length)
                                date.push(seps.shift());
                        date.push(val[format.parts[i]]);
                }
                return date.join('');
        },
        //-----
&#13;
        .datepicker tbody tr:hover {
        	background-color: #eee;
        }
        .datepicker tbody tr:hover td,
        .datepicker tbody tr td.active {
        	border-radius: 0;
        }
        .datepicker tbody tr:hover td:last-child,
        .datepicker tbody tr td.active:last-child {
        	border-radius: 0 3px 3px 0;
        }
        .datepicker tbody tr:hover td:first-child,
        .datepicker tbody tr  td.active:nth-child(2) {
        	border-radius: 3px 0 0 3px;
        }
&#13;
        <!--RefLinks-->
        <link href="~/libraries/bootstrap-datepicker-1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet">
        <script src="~/libraries/bootstrap-datepicker-1.6.4/js/bootstrap-datepicker.js"></script>
 
        <!--OnBody-->
        <input id="datepicker2" class="datepicker4" style="width: 300px;" type="text">

        <!--OnScriptSection-->
        $(function ()
        {
            var $weekPicker = $("#datepicker2");
            $weekPicker.datepicker
                (
                    {
                        autoclose: true,
                        format: 'ww', //'dd-M-yyyy',
                        calendarWeeks: true,
                        //maxViewMode: 0,
                        weekStart: 1
                    }
                )        
&#13;
&#13;
&#13;