How To Get startDate and endDate from RangePicker from ANTD.DESIGN - javascript

i'm working ing a react js project and I'm using antd.design Library to show a RangePicker
what i'm trying to solve is how can i get the start date and the end date from this RangePicker when user select a period
that's my code :
handleChangeDebut =range => {
const valueOfInput1 = moment(range.startDate).format();
const valueOfInput2 = moment(range.endDate).format();
console.log('start date',valueOfInput1);
console.log("end date",valueOfInput2);
}
<DatePicker.RangePicker
style={{ width: "100%" }}
getPopupContainer={trigger => trigger.parentNode}
onChange={this.handleChangeDebut}
/>
the issue is on my handleChange function , i always get the date of the current day
is there any attributes in antd design that give us the startDate and the EndDate Selected ?
Thank you for your precious help .

From the documentation, this is the signature of the onChange function function(dates: moment, moment, dateStrings: string, string), It looks like start and end date are passed as an array in the first param:
handleChangeDebut = (range) => {
const valueOfInput1 = range[0].format();
const valueOfInput2 = range[1].format();
console.log('start date',valueOfInput1);
console.log("end date",valueOfInput2);
}

Related

MomentJS - shifts the date by a day after format operation

To work with one component, I need a unix date, to work with another - a text display of days, months and years. Also, each of them can be changed and the second one must synchronize its date with the first one. Now I'm getting an infinite loop because the format operation always shifts the date for me by one day. Can you please tell me how can I get the correct date??
const formatTime = ({ date, format = DEFAULT_FORMAT }: OwnProps): string => {
const inutc = utc(date);
console.log('inutc', inutc)
const formatted = inutc.format(format);
return formatted
}
Okay, i fixed it by replaced utc() to moment() like this:
const formatTime = ({ date, format = DEFAULT_FORMAT }: OwnProps): string => {
return moment(date).format(format)
}

Array sort with React.useState breaks when adding certain date

I'm trying to add a date in a list and sort that list to ascending every time I add a new date. Everything is fine, the list is being resorted when every new data is inserted, but if I start to add this date 13/02/22 the re-sorting will seem to have stopped and the new date inserts will be will just stack to each other/latest insertion will be the last regardless of its actual date.
Here is my code when adding a date to the list. And the useEffect in here is my sorting logic. As you can see I sort my list of dates by calling the setAddedOpens which is a React.useState.
const [addedOpens, setAddedOpens] = React.useState(defaultOpens);
const [toggleSort, setToggleSort] = React.useState(false);
const _addOpens = () => {
for (let week = 0; week <= repeatWeeks; week++) {
const OFI = new Date(getValues('OFIdate'));
setAddedOpens((prevOpens) => [
...prevOpens,
{
ofi: format(OFI.setDate(OFI.getDate() + 7 * week), 'dd/MM/yyyy'),
start: format(getValues('startTime'), 'hh:mm a'),
end: format(getValues('endTime'), 'hh:mm a')
}
]);
}
setToggleSort((toggle) => !toggle);
};
React.useEffect(() => {
setAddedOpens([...addedOpens].sort((a, b) => new Date(a.ofi) - new Date(b.ofi)));
}, [toggleSort]);
Don't mind the other parts of my code here. Because I also have a feature you can bulk add dates. But in the meantime let's say I'm just adding a single date every time I click ADD and thatrepeatWeeks state is always 0.
I'm not so sure what could be the problem is. Maybe I'm missing something in my logic? Or this has something to do with dates or date formatting? Why is the sorting getting erroneous once I added the date 13/02/22 ?
Thanks in advance.
Try to add an additional property to the Object, let's call it ofi_sorting, that stores the date in the yyyy-MM-dd format and use that field for sorting the values:
setAddedOpens((prevOpens) => [
...prevOpens,
{
ofi: format(OFI.setDate(OFI.getDate() + 7 * week), 'dd/MM/yyyy'),
ofi_sorting: format(OFI.setDate(OFI.getDate() + 7 * week), 'yyyy-MM-dd'),
start: format(getValues('startTime'), 'hh:mm a'),
end: format(getValues('endTime'), 'hh:mm a'),
},
]);
}
setToggleSort((toggle) => !toggle);
};
React.useEffect(() => {
setAddedOpens(
[...addedOpens].sort((a, b) => a.ofi_sorting - b.ofi_sorting)
);
}, [toggleSort]);

How to execute a function right after state gets updated with Hooks in React Native?

As my trivial experience in Javascript and React Native, I've been struggling with how to execute a function call checkValidDate right after my state for the dates have been updated.
I'm using react-native-modal-date-time-picker to choose the date.
Here's my code:
const [chosenStartDate, setChosenStartDate] = useState('');
const [chosenStartDate_unix, setChosenStartDate_unix] = useState(null);
const [chosenEndDate, setChosenEndDate] = useState('');
const [chosenEndDate_unix, setChosenEndDate_unix] = useState(null);
const handleConfirm = (day) => {
hideDatePicker(); // Set isDatePickerVisible to false
if(chosenMode){ // If true, calendar shows up for choosing starting date, false --> for choosing ending date
setChosenStartDate(moment(day).format('MMMM Do YYYY, h:mm:ss a'));
setChosenStartDate_unix(parseInt((new Date(moment(day).format()).getTime())/60000));
// Convert date to epoch time
}else{
setChosenEndDate(moment(day).format('MMMM Do YYYY, h:mm:ss a'));
setChosenEndDate_unix(parseInt((new Date(moment(day).format()).getTime())/60000));
checkValidDate(chosenStartDate_unix,chosenEndDate_unix)
// --> I know that the dates only get updated after the handleConfirm has been executed
// --> So basically, the chosenEndDate_unix passed in checkValidDate at this moment is still
// null. Therefore, I can't check it correctly
}
};
const checkValidDate = (start, end) => {
console.log('Checking')
console.log('chosenEndDate_unix', chosenEndDate_unix);
console.log('chosenStartDate_unix', chosenStartDate_unix);
if(start && end){
((end - start) >= 5)
? (console.log('VALID'))
: (alert('Please travel aleast 5 minutes, life is worth explored!'), setChosenEndDate(''))
}
}
//...
return(
//...
{isDatePickerVisible && (
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode={mode}
onConfirm={(day) => {
handleConfirm(day)
// I tried to execute the checkValidDate here, but it also doesn't work
}}
onCancel={hideDatePicker}
/>
)}
)
Basically, I have 2 buttons.
One for choosing a startDate which doesn't need to be checked.
Another for choosing an endDate which needs to be checked whether It's longer that startDate for at least 5 minutes or not
When pressing startDate button, chosenMode will be set to true and vice versa for endDate button
handleConfirm is the function we'll execute when we press the OK button on the calendar. As designed in react-native-modal-date-time-picker, only when we press OK will the date chosen be passed to the onConfirm prop
How can we execute the checkValidDate right after the chosenEndDate and chosenEndDate_unix has been updated?
PLEASE HELP ME
You can use useEffect. The checkValiddate is called when chosenEndDate or chosenEndDate_unix changed.
useEffect(()=>{
checkValiddate()
}, [chosenEndDate, chosenEndDate_unix]);
The official document has more info of how it works: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
Thank you very much Yupeng Li. Thank to your suggestion I've come up with the solution
By the way, when we place 2 dependencies which will change at the same time like that. checkValidDate() will be executed twice. So we'll put only 1 dependency which is chosenEndDate_unix
useEffect(() => {
if(!chosenMode) checkValidDate(chosenStartDate_unix, chosenEndDate_unix)
}, [chosenEndDate_unix])

match values start or end dates in javascript

I am facing an issue in javascript dates, i want to match slot dates comparing start_date or end_date.
my component
{this.state.data && this.state.data.length
? this.state.data
.filter(data => {
const date = new Date(data.start_date);
const enddate = new Date(data.end_date);
console.log(date); //start
console.log(enddate); //end
return date > prevDate && date < nextDate;
})
.map(({ cust_full_name, start_date }, index) => (
<div class="row" key={index}>
slot: {index + 1}
<p>{start_date}</p>
<p>{cust_full_name}</p>
</div>
))
: null}
working demo:
https://codesandbox.io/s/lucid-dream-gl3l7?file=/src/App.js
what should i do? can anyone help me?
Edit: Your slot values in your state are in arrays but when you pass them to date you aren't accessing the string value.
slot1 : ["date"]
Incorrect: new Date[slot1]
Correct: new Date[slot[0]]
In your sandbox it seems you never populated newprevious and newseconddate here:
const prevDate = new Date(this.state.newprevious);
const nextDate = new Date(this.state.newseconddate);
Once i populated those in the above state section, it seems to work. I do also suggest maybe turning Date into something like epoch; so the numbers are easier to work with (Get epoch for a specific date using Javascript)

React-Native/Firestore - Search by date

I'm trying to create a search filter where you can filter by specific date. Not sure what the problem is. It's a react-native project where i'm using hooks (useEffect) to read firestore data. That part work wery well. However i want to apply a searchfilter where you can select both location and date.
The location part works like a charm. Here is some code example:
useEffect(() => {
db.collection("Name of the collection")
.where("location", "==", props.searchLocation)
.where("date", "==", props.searchDate)
.onSnapshot(snapshot => {
If i delete the date query part then the location part works fine. Also if i change == to >= on the date part then it displays the data from the selected date and forward.
useEffect(() => {
db.collection("Name of collection")
.where("location", "==", props.searchLocation)
.where("date", "=<", props.searchDate)
.onSnapshot(snapshot => {
But the thing is that i want it to only display the data from the selected date. If i console.log the props.SearchDate then the format looks like this:
2019-11-09T00:00:00.000Z.
I'm using react-native base DatePicker to be able to choose date and i also got Moment.js to display the date.
Any thoughts on this? Does it have anything to do with the date format and time format?
Update 1
The code im using to set the props.Searchdate and a screenshot of console.log() + instanceof Date
Screen.js
const [searchDate, setSearchDate] = useState(new Date());
console.log(searchDate instanceof Date);
console.log(searchDate);
component.js
const datePicker = value => {
new Date(props.setSearchDate(value));
};
expo console screenshot
Update 2 - My solution
I did solve it with creating two conts at the beginning of the useEffect where i set the time of the chosen date.
Then i query the data by two .where() arguments.
This is my solution if anyone else strugeling with the same thing. However i dont know if it is the best practice.
useEffect(() => {
const date1 = new Date(props.searchDate.setHours(0, 0, 0, 0));
const date2 = new Date(props.searchDate.setHours(23, 59, 59, 59));
console.log(date1);
console.log(date2);
db.collection("Name of collection")
.where("location", "==", props.searchLocation)
.where("date", ">=", date1)
.where("date", "<=", date2)

Categories