Reputation: 369
I am building a calendar where people can select a range of days from a visual calendar.
Clicking on a date will select it as a "from" or "to" date. For example, if I click on 1januari and 5 January. 1 January will be the "from" date while 5 January will be the "to" date. Easy right?
Now the thing is if a user clicks on a new date, I will need to update the current "from" and "to" dates. Using
stringToDate(date.dateTime) > stringToDate(this.state.fromDate)
lets me know if the incoming date is later then the current "from date" with I can use to change the current "to" date to the incoming Date because 7 January comes after 5 January with "must" mean the user wanted to update their "to" date.
A similar function does the same thing for the "from" date. This works great and all but this means that users can't select a "from" date that comes later than their original "from" date.
What I want to achieve is the following: Calculate if the incoming date is closer to the "from" date or the "to" date. So if a user starts with 1 and 5 January and clicks on 2 January I can assume that he wants to update his "from" date.
My current function looks like this:
handleFromDateSelected(date) {
let updatedFromDate = '';
let updatedToDate = '';
if (this.state.fromDate) {
if (stringToDate(date.dateTime) > stringToDate(this.state.fromDate)) {
updatedFromDate = this.state.fromDate;
updatedToDate = date.dateTime;
} else {
updatedFromDate = date.dateTime;
updatedToDate = this.state.fromDate;
}
} else {
updatedFromDate = date.dateTime;
}
this.setState({
fromDate: updatedFromDate,
toDate: updatedToDate,
});
}
Upvotes: 0
Views: 97
Reputation: 15247
If you really want to check from which date the new one is closed, which is, in my opinion not a good choice, you can convert all 3 dates (from, to and new) to timestamp and compare the absolute difference. The lowest one means this is closer to the new one.
in example, let's assume dateFrom
, dateTo
and newDate
are date objects :
//Returns true if newDate is closer to dateFrom
function isFromDateCloser(dateFrom, dateTo, newDate)
{
timeStampFrom = dateFrom.getTime();
timeStampTo = dateTo.getTime();
timeStampNew = newDate.getTime();
return (Math.abs(timeStampFrom - timeStampNew) < Math.abs(timeStampTo - timeStampNew));
}
if (isFromDateCloser(dateFrom, dateTo, newDate))
dateFrom = newDate;
else
dateTo = newDate;
In that example, I've arbitrary choosen that if new date is strictly between both dates, the new date will be dateTo. If you prefer the that the from become the new date, replace in the return <
by <=
Upvotes: 2
Reputation: 220
In your case
var firstDate = new Date(date.dateTime);
var secondDate = new Date(this.state.fromDate)
if (firstDate.getTime() > secondDate .getTime()){
// do something here
}
Upvotes: 0