如何在 React JS DateRangePicker 中设置日期范围选择?

How to set date range selection in react JS DateRangePicker?

我在我的 React JS 应用程序中使用 'DateRangePicker' 组件。 我试图将开始日期限制为仅过去 6 个月,两者之间的区别 开始日期和结束日期不应超过 1 个月。 我写了下面的代码

isOutsideRange = (day) => {
  if (day > moment()) return true;
  else if (this.state.startDate) {
    if (day > moment(this.state.endDate)) return true;
    if (day < moment().subtract(6, 'months')) return true;
    else return false;
  } else if (this.state.endDate) {
    if (day > moment(this.state.endDate)) return true;
    if ((moment(this.state.endDate) > (moment(this.state.startDate).subtract(1, 'month')))) return true;
    else return false;
  }
}

这里是 UI 代码

<DateRangePicker
  startDate={this.state.startDate}
  startDateId="validFromDate"
  endDate={this.state.endDate}
  endDateId="validToDate"
  onDatesChange={({ startDate, endDate }) =>
    this.handleValidDatesChange(startDate, endDate)
  }
  focusedInput={this.state.ofrFocusedInput}
  onFocusChange={(ofrFocusedInput) => this.setState({ ofrFocusedInput })}
  isOutsideRange={(e) => this.isOutsideRange(e)}
  showDefaultInputIcon={true}
  small={true}
  minimumNights={0}
  hideKeyboardShortcutsPanel={true}
  showClearDates={true}
  min={this.maxDate}
  shouldDisableDate={({ startDate }) => this.disablePrevDates(startDate)}
  // minDate={subDays(new Date(), 10)}
  displayFormat={() => "DD/MM/YYYY"}
/>;

我试过调试,但没有用。 有人可以建议解决方案吗?

if (day.isAfter(moment()) || 
   !day.isAfter(moment().subtract(6,'months'))) return true;

要检查一个时刻是否在其他两个时刻之间,可选择查看单位比例(分钟、小时、天等),您应该使用:

moment().isBetween(moment-like, moment-like, String, String);
// where moment-like is Moment|String|Number|Date|Array

例如,如果您需要检查 today - 6months <= someDate <= today,您可以使用如下内容:

// returns TRUE if date is outside the range
const isOutsideRange = date => {
    const now = moment();
    return !moment(date)
             .isBetween(now.subtract(6, 'months'), now, undefined, '[]');
    // [] - match is inclusive
}

更多详情,请查看Is Between docs。这个方法很灵活,比如可以独占,也可以包含。

现在,第二个条件。如果你想检查是否 endDate - startDate <= 1 month,你也可以玩 moments 来实现。

// so if you add 1 month to your startDate and then your end date
// is still before the result or the same - you can say the duration
// between them is 1 month
const lessThanMonth = (startDate, endDate) => {
    return endDate.isSameOrBefore(moment(startDate).add(1, 'months'));
}