I want to select a period with a date array or selecting start date and end date.
I just saw examples with static dates
i use this code.
import React, {useState} from 'react';
import {View} from 'react-native';
import BaseModal from './index';
import Button from 'components/Button';
import _isEmpty from 'lodash/isEmpty';
import moment from 'moment';
import {Calendar} from 'react-native-calendars';
const ModalCalendar = ({showModal, onCloseModal}) => {
const [startDay, setStartDay] = useState({});
const [endDay, setEndDay] = useState({});
const [periodDay, setPeriodDay] = useState({});
const getPeriod = (startTimestamp, endTimestamp) => {
const period = {};
let start = moment.unix(startTimestamp);
const end = moment.unix(endTimestamp);
while (end.isAfter(start)) {
period[start.format('YYYY-MM-DD')] = {
color: 'green',
startingDay: moment(start).unix() === startTimestamp,
};
start = start.add(1, 'days');
}
period[end.format('YYYY-MM-DD')] = {
color: 'green',
endingDay: true,
};
return period;
};
const setDay = objDay => {
const {dateString, day, month, year} = objDay;
const timestamp = moment(dateString).unix();
if (_isEmpty(startDay) || (!_isEmpty(startDay) && !_isEmpty(endDay))) {
const period = {
[dateString]: {
color: 'yellow',
endingDay: true,
startingDay: true,
},
};
const newObjDay = {...objDay, timestamp};
setStartDay(newObjDay);
setPeriodDay(period);
setEndDay({});
} else {
const {timestamp: savedTimestamp} = startDay;
if (savedTimestamp > timestamp) {
const period = getPeriod(timestamp, savedTimestamp);
setPeriodDay(period);
} else {
const period = getPeriod(savedTimestamp, timestamp);
setPeriodDay(period);
}
}
};
return (
<BaseModal show={showModal}>
<View>
<Calendar
onDayPress={setDay}
markedDates={periodDay}
markingType={'period'}
/>
<Button onClick={onCloseModal} />
</View>
</BaseModal>
);
};
export default ModalCalendar;
Most helpful comment
i use this code.