js-datepicker日期范围基于开始的结束

时间:2019-01-07 19:04:01

标签: javascript date datepicker

我正在使用此日期选择器https://www.npmjs.com/package/js-datepicker,并且大部分时间都在使用它。但是,我想根据开始日期中选择的内容来确定第二个日期的开始和结束日期。

HTML:

    <input type="text" name="message[dateStart][]" class='date date-start' placeholder="Start Date">

    <input type="text" name="message[dateEnd][]" class='date date-end' placeholder="End Date">  

当前javascript

// set date to 2 weeks from now calculated in milliseconds
var afterTwoWeeks = new Date(+new Date + 1209600000);

var pickerEnStart = datepicker('.date-start', {
  // dateSelected: new Date(2099, 0, 5)
  minDate: new Date(afterTwoWeeks),
  startDate: new Date(afterTwoWeeks),
  noWeekends: true,
  formatter: (input, date, instance) => {
    const value = date.toLocaleDateString()
    input.value = value // => '1/1/2099'
  }
})


var pickerEnEnd = datepicker('.date-end', {
  // dateSelected: new Date(2099, 0, 5)
  minDate: new Date(afterTwoWeeks),
  startDate: new Date(afterTwoWeeks),
  noWeekends: true,
  formatter: (input, date, instance) => {
    const value = date.toLocaleDateString()
    input.value = value // => '1/1/2099'
  }
})

我尝试了几件事,但无法根据选择的开始日期获取开始/结束的结束日期。

1 个答案:

答案 0 :(得分:1)

这似乎以我期望的方式工作。

HTML

   <input type="text" name="message[dateStart][]" class='date date-start' placeholder="Start Date">

   <input type="text" name="message[dateEnd][]" class='date date-end' placeholder="End Date">  

   <input type="button" id="reset" name="reset" value="Reset">

JS

var afterTwoWeeks = new Date(+new Date + 1209600000)

// none of this works well if we can't clear dates
var reset = document.getElementById('reset')
reset.onclick = function() {
  pickerEnStart.setDate()
  pickerEnEnd.setDate()
}

var pickerEnStart = datepicker('.date-start', {
  minDate: new Date(afterTwoWeeks),
  startDate: new Date(afterTwoWeeks),
  noWeekends: true,
  formatter: (input, date, instance) => {
    const value = date.toLocaleDateString()
    input.value = value 
  },
  id: 1,
  onSelect: (instance, date) => {
    // set the minimum date
    instance.setMin(date)
    // if end date not selected...
    if(!pickerEnEnd.dateSelected) { 
      // set the end date to force the calendar to display that month
      pickerEnEnd.setDate(new Date(date.getTime() + 1000*60*60*24), true)
      pickerEnEnd.firstTime = true
    }
  }
})

var pickerEnEnd = datepicker('.date-end', {
  minDate: new Date(afterTwoWeeks),
  startDate: new Date(afterTwoWeeks),
  noWeekends: true,
  formatter: (input, date, instance) => {
    const value = date.toLocaleDateString()
    input.value = value
  }, 
  id: 1,
  onSelect: (instance, date) => {
    instance.setMax(date)
  },
  onShow: function(instance) {
    // if this is the first time we're seeing this calendar...
    if (instance.firstTime) {
      // get rid of the end date we set to force it to this month
      instance.setDate();
      instance.firstTime = false;
    }
  },
})