如何在Bootstrap Datepicker中添加天数时排除周末?

时间:2017-01-17 02:41:44

标签: javascript jquery twitter-bootstrap datepicker

我使用bootstrap datepicker。选择日期时,我想添加所选日期+3 不包括周末(也可能是假期的一些随机日期)并将其放在文本框中。因此,如果所选日期是星期五,25日,那么文本框值应该是星期三,30日。这是我目前的剧本:

$('.date_get .date').datepicker({
    startView           : 0,
    todayBtn            : "linked",
    forceParse          : false,
    autoclose           : true,
    endDate             : "now",
    format              : "dd/mm/yyyy",
    todayHighlight      : true,
    daysOfWeekDisabled  : [0,6]
}).on('changeDate', function (selected) {

    //DATE 2 = DATE 1 + 3 Days
    var tgl = new Date(selected.date.valueOf() + (1000 * 60 * 60 * 24 * 3)); //Chosen date +3 days

    var hr  = tgl.getDate();
    var bln = tgl.getMonth() + 1; //Januari == 0

    if(bln <10)
    bln = "0"+bln;
    else
    bln = bln;

    var thn      = tgl.getFullYear();
    var hari_ini = hr + "/" + bln + "/" + thn;

    $('.date_tgt').val(hari_ini);
});

3 个答案:

答案 0 :(得分:0)

您需要使用setDate功能添加三天。 试试这个

var result = new Date(yourDate);
result.setDate(result.getDate() + 3);

答案 1 :(得分:0)

您可以使用moment.js在javascript中获取day of week。例如:

var selectedDate = moment(new Date(selected.date.valueOf()); //create moment instance
var dayOfWeek = selectedDate.day(); //will return 0-6, represent sunday-saturday

然后你可以制作算法来调整你的需要,例如将星期几(0-6)映射到它的附加值。像这样:

var addedDays = [3, 3, 3, 5, 5, 5, 4]
//example: 
var selectedDate = moment("2017-01-13"); //friday last week
var resultDate = selectedDate.add(addedDays[selectedDate.Day()], 'days');
//resultDate = 13th (friday) + 5 days = 18th (wednesday)

答案 2 :(得分:0)

如果我理解正确,你可以试试这个。

  var date1 = new Date("Jan 20 2017 12:00:00 GMT+0800"); 
  var date2 = new Date(); 
  date2.setDate(date1.getDate()+5); //added 5 days
  var answer= dateDifference(date1,date2); 

  console.log(answer);

 function dateDifference(start, end) {

  // Copy date objects so don't modify originals
  var s = new Date(+start);
  var e = new Date(+end);
  var flag = new Date(+start);
  var numberOfWeekEnds = 0; 

  // Set time to midday to avoid dalight saving and browser quirks
  s.setHours(12,0,0,0);
  e.setHours(12,0,0,0);

  // Get the difference in whole days
  var totalDays = Math.round((e - s) / 8.64e7);

  // Get the difference in whole weeks
  var wholeWeeks = totalDays / 7 | 0;

  // Estimate business days as number of whole weeks * 5
  var days = wholeWeeks * 5;

  // If not even number of weeks, calc remaining weekend days
  var lasta
  if (totalDays % 7) {
    s.setDate(s.getDate() + wholeWeeks * 7);

    while (s < e) {
      s.setDate(s.getDate() + 1);

      // modified
      if (s.getDay() != 0 && s.getDay() != 6) {
        flag.setDate(flag.getDate() + 1 +numberOfWeekEnds);
        numberOfWeekEnds = 0
      }
      else{
        numberOfWeekEnds++;
      }
    }
  }
  return flag;
}

基本上我做的是修改了这个answer中的函数来检查一天是否是工作日。

您可以使用date1date2进行进一步检查。