我在我的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"}
/>;
我试着调试了一下,但是没有用,谁能给个建议?
要检查一个时刻是否在其他两个时刻之间,可以选择查看单位比例(分钟,小时,天等),你应该使用。
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
}
更多细节,请查看 是docs之间. 这种方法非常灵活,例如,你可以有排他性或包容性的匹配。
现在,第二个条件。如果你想检查 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'));
}
if (day.isAfter(moment()) ||
!day.isAfter(moment().subtract(6,'months'))) return true;