I have two dates from-date
& to-date
.
I have to compare them from existing dates shown below, whether any of the day fall between them or not using php?
i can do for single date checking ,but i am confuse for the two date checking.
Example: i have to check these dates:-> from= 15 March 2013
& 15 April 2013
between the following dates whether any days falls in between these two date or not.
# from date to-date
-----------------------------------------
1 01 April 2013 30 April 2013 //here we will find as falling
2 01 May 2013 15 May 2013
3 01 June 2013 20 June 2013
Currently,in my mind not even a single logic is coming to try. Please give me any logic or suggestions regarding this issue..
The simplest way to compare dates is to convert them to a unix timestamp
Because the unix timestamp is an integer, you can simply use relational operators to compare them.
Example
// set some example data
$referenceDate = '01 April 2013';
$fromDate = '01 January 2013';
$toDate = '01 June 2013';
// convert dates to timestamps (strings to integers)
$referenceTimestamp = strtotime( $referenceDate );
$fromTimestamp = strtotime( $fromDate );
$toTimestamp = strtotime( $toDate );
// isBetween is Boolean TRUE if reference date is greater or equal fromDate and smaller or equal toDate
$isBetween = $referenceTimestamp >= $fromTimestamp and $referenceTimestamp <= $toTimestamp;
EDIT 1
To actually answer your question:
You have two ranges you need to test for overlap, this question has been answered here What's the most efficient way to test two integer ranges for overlap?
// our two ranges overlap if the following conditions are met
$dateRangeOverlaps = $referenceFromTimestamp <= $toTimestamp and $fromTimestamp <= $referenceToTimestamp;
Please try the code,
$ourdate = strtotime('1 April 2013'); // Your date which is to be checked
$from = strtotime('15 March 2013'); // From date
$to = strtotime('15 April 2013'); // To date
if ($ourdate >= $from && $ourdate <= $to)
{
echo "Date falls";
}
else
{
echo "No Date falls";
}
If you need to check several dates, pass it as an array, like below...
$i=0;
$dates= array("11 April 2013","16 April 2013");
foreach($dates as $ourdates)
{
$ourdate= strtotime($ourdates); //Your dates to be checked
$from = strtotime('15 March 2013'); // From date
$to = strtotime('15 April 2013'); // To date
if ($ourdate >= $from && $ourdate <= $to)
{
$i++;
}
}
if($i>0)
{
echo "Date falls";
}
else
{
echo "No Date falls";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.