Javascript Date Range Between Date Range
I'm trying to have an IF check to see if X date range is between Y date range. But it's not returning the correct true/false on the correct time: var startdate = new Date('06/06/20
Solution 1:
If you're trying to detect full containment, that is fairly easy. (Also, you don't need the explicit return true/false
, because the condition is a boolean anyway. Just return it)
// Illustration://// startdate enddate// v v// #----------------------------------------#//// #----------------------#// ^ ^// startD endDreturn startD >= startdate && endD <= enddate;
An overlap test is slightly more complex. The following will return true
if the two date ranges overlap, regardless of order.
// Need to account for the following special scenarios//// startdate enddate// v v// #----------------#//// #----------------------#// ^ ^// startD endD//// or//// startdate enddate// v v// #----------------#//// #------------------#// ^ ^// startD endDreturn (startD >= startdate && startD <= enddate) ||
(startdate >= startD && startdate <= endD);
@Bergi's answer is probably more elegant, in that it just checks the start/end pairs of the two date ranges.
Solution 2:
To check if they overlap with any days, use
if (endD >= startdate && startD <= enddate)
which is equivalent to
if ( !(endD < startdate || startD > enddate)) // not one after the other
Solution 3:
In your example, the new dates are both outside the range.
If you want to check if there is any overlap between the date ranges, use:
return (endD >= startdate && startD <= enddate);
Solution 4:
here is the logic in nodejs
exportconstisDateOverlaped = (firstDateRange: { from: Date; to: Date }, secondDateRange: { from: Date; to: Date }) => {
// f-from -----------f-to// s-from -------------- s-toconst overlappedEnd =
firstDateRange.from <= secondDateRange.from && firstDateRange.to >= secondDateRange.from && firstDateRange.to <= secondDateRange.to// f-from ----------------------- f-to// s-from --------- s-toconst overlappedBetween = firstDateRange.from <= secondDateRange.from && firstDateRange.to >= secondDateRange.to// f-from -----------f-to// s-from -------------- s-toconst overlappedStart =
firstDateRange.from >= secondDateRange.from && firstDateRange.from <= secondDateRange.to && firstDateRange.to >= secondDateRange.toreturn overlappedEnd || overlappedBetween || overlappedStart
}
Post a Comment for "Javascript Date Range Between Date Range"