首页 > 解决方案 > 如何在 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;
  }
}

这是用户界面代码

<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"}
/>;

我试图调试,但它不工作。有人可以提出解决方案吗?

标签: reactjsdaterangepicker

解决方案


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

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。这种方法非常灵活,例如,您可以进行独占或包含匹配。

现在,第二个条件。如果你想检查 if endDate - startDate <= 1 month,你也可以玩一些时刻来实现这一点。

// 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'));
}

推荐阅读