reactjs - React 和 momentjs - 检查两个日期数组并返回布尔值
问题描述
我有这个日历组件并handleDayPickerChange
处理日历上的日期选择。在下面的代码中,有
const today = moment();
type SelectDate = SELECT_DATE.START | SELECT_DATE.END;
type DayDataSource = {
date: string,
bookable: boolean,
};
type Props = {
onSubmit: () => mixed,
spaceId: string,
minimumDuration: number,
client: ApolloClient<any>,
days: Array<DayDataSource>,
};
type State = {
month: moment,
selectDate: ?SelectDate,
};
const GET_SELECTED_DATES = gql`
{
selectedDates @client {
startOn
endOn
}
}
`;
class Calendar extends Component<Props, State> {
state = {
month: today,
selectDate: null,
};
handleStartDateClick = () => {
this.setState({ selectDate: SELECT_DATE.START });
};
handleEndDateClick = () => {
this.setState({ selectDate: SELECT_DATE.END });
};
handleDayPickerChange = async (e, startDate, endDate) => {
console.log("changing");
if (startDate && endDate ) {
return this.handleDateSubmit(startDate, endDate);
} else {
const newDates = convertDatesToPeriodAttribute({ endOn: endDate, startOn: startDate });
//write the selectedDates
await this.props.client.writeData({
data: {
selectedDates: newDates,
},
});
startDate ? this.setState({ selectDate: SELECT_DATE.END }) : this.setState({ selectDate: SELECT_DATE.START });
}
};
handleDateSubmit = async (startDate, endDate) => {
await this.props.client.writeData({
data: {
selectedDates: convertDatesToPeriodAttribute({ endOn: endDate, startOn: startDate }),
},
});
this.setState({ selectDate: null });
};
handleDayPickerClose = () => {
this.setState({
selectDate: null,
});
};
handleClearDates = (startDate, endDate) => () => {
if (startDate || endDate) {
this.props.client.writeData({
data: {
selectedDates: [],
},
});
this.setState(() => ({
selectDate: SELECT_DATE.START,
}));
} else {
this.handleDayPickerClose();
}
};
handleMonthChange = (e, month) => {
this.setState({ month });
};
calculateBookingLength = (startDate, endDate): number => {
return startDate && endDate ? endDate.diff(startDate, 'days') + 1 : 0
};
render() {
const { month, selectDate } = this.state;
const { onSubmit, spaceId, minimumDuration, days } = this.props;
return (
<Query query={GET_SELECTED_DATES}>
{({ data: { selectedDates }, loading, error}) => {
if (loading) return null;
if (error) return null;
const selectedDatesMoment = convertDatesToMomentLocal(selectedDates);
const startDate = selectedDatesMoment.length ? selectedDatesMoment[0].startOn : null;
const endDate = selectedDatesMoment.length ? selectedDatesMoment[0].endOn : null;
const bookingLength = this.calculateBookingLength(startDate, endDate);
const validSelection = isSelectionValid({
selectedDates: [{startOn: startDate, endOn:endDate}],
minimumDurationInDays: minimumDuration,
sparse: false,
});
return (
<div>
<div className={css.section} data-testid="simplified-calendar">
<div className={css.datesHeadline}>{'Dates'}</div>
<div
className={cx(
css.dayRangeContainer,
selectDate ? css.dayRangeContainerActive : null,
)}
>
<DurationDropdownTarget
className={cx(
css.dayPickerTarget,
selectDate ? css.dayPickerTargetActive : null,
)}
iconVisibilityClass={css.iconVisible}
startDate={startDate}
endDate={endDate}
id="tenancyDuration"
selectDate={selectDate}
onStartDateClick={this.handleStartDateClick}
onEndDateClick={this.handleEndDateClick}
onClearDatesClick={this.handleClearDates(startDate, endDate)}
active={!!selectDate}
/>
</div>
{selectDate && (
<div className={css.datePickerContainer}>
<DayRangePicker
month={month}
selectDate={selectDate}
startDate={startDate}
endDate={endDate}
onInteraction={this.handleDayPickerChange}
onMonthChange={this.handleMonthChange}
isDisabled={(d) => d.isBefore(today, 'day') || days.find(day => day.date === d.format('YYYY-MM-DD') && !day.bookable)}
classNames={{header: 'fs-ignore-rage-clicks'}}
/>
</div>
)}
</div>
{validSelection && (
<div className={css.section}>
<Recap simplifiedCalendarEnabled={true} spaceId={spaceId} sparse={false} showDeposit={false} />
</div>
)}
{(bookingLength < minimumDuration && bookingLength > 0) && (
<div className={css.section}>
<MinimumDurationNotification minimumDuration={minimumDuration} />
</div>
)}
<div className={css.section}>
<BookingButtonContainer
className={css.submitButton}
spaceId={spaceId}
disabled={!validSelection}
onClick={onSubmit}
/>
</div>
</div>
);
}}
</Query>
);
}
}
export default withApollo(Calendar);
现在我想做一些事情来检查 startDate 和 endDate 之间的日期是否有任何不可用的日期 - 然后它将返回 false。所以像..
checkIfSelectionIsGood = (startDate, endDate) => {
//check days from startDate to endDate against days prop..
//return true or false
}
我该怎么办?
解决方案
您可以使用getTime()尝试此操作,
checkIfSelectionIsGood = (startDate, endDate) => {
//check days from startDate to endDate against days prop..
//return true or false
let startDate = new Date(startDate).getTime();
let endDate = new Date(endDate).getTime();
//Assuming `this.props.days` is array
this.props.days.map((day)=>{
let day = new Date(day).getTime();
if(day>=startDate && day<=endDate){
return true;
}else{
return false;
}
})
}
推荐阅读
- firebase - Flutter 如何优化 Firestore 存储读取以防止大量不必要的读取
- python - 将二进制 Pandas 数据框折叠成一列
- java - 在 Java 中使用双冒号表达式的问题
- swift - 动画卡在swiftUI中进入网格
- java - MapStruct:对象类的映射
- c# - LINQ 使用条件 where 生成错误查询
- c# - NLog TemplateParserException,应为'{'但在格式中找到'\'?
- python - 如何解决 Jupyter 中未找到模块的错误
- cucumber - 我们可以在文件 karateconfig.js 中使用“调用读取”吗
- sql - 如何获得具有硬编码值的表的计数(该表是选择中创建的表)?