Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Date Range Check

Tags:

php

I have 2 date ranges

[contract_start_date] => 2011-10-20 [contract_end_date] => 2011-10-29

and I want to verify if the dates below are in range of the date range above

 2011-05-05 and 2011-10-10

the dates given must not in any way exceed the range of the contract

Is there a function for this in PHP ?

like image 714
BoqBoq Avatar asked Jun 20 '11 13:06

BoqBoq


People also ask

How do you check a date is between two dates in PHP?

The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.

How do you know if a date is between two dates?

To check if a date is between two dates:Check if the date is greater than the start date and less than the end date. If both conditions are met, the date is between the two dates.

What does date () do in PHP?

PHP date() Function The PHP date function is used to format a date or time into a human readable format. It can be used to display the date of article was published. record the last updated a data in a database.


3 Answers

See:: http://php.net/manual/en/datetime.diff.php

$datetime1 = new DateTime('2011-10-20');
$datetime2 = new DateTime('2011-10-29');

//PHP 5.3.0
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

//PHP 5.2.2
var_dump($datetime1 < $datetime2);

$datetime3 = new DateTime('2011-05-05');
$datetime4 = new DateTime('2011-10-10');

if ($datetime3 > $datetime1 && $datetime2 > $datetime1 && $datetime3 < $datetime2 && $datetime2 < $datetime2) {
    //valid range
}//end if
like image 180
turbod Avatar answered Oct 30 '22 11:10

turbod


This should give you exactly what you're looking for:

 define(CONTRACT_START, "2011-10-20");
 define(CONTRACT_END, "2011-10-29");

 function checkDateRange($dateArray)
 {
    foreach($dateArray as $dateStr)
    {
        $curDate = strtotime($dateStr);
        if($curDate < strtotime(CONTRACT_START) || $curDate > strtotime(CONTRACT_END))
        {
            return false;
        }   
    }   
    return true;
 }   


$dates = array( 0 => "2011-10-02", 1 => "2011-10-25");

if(checkDateRange($dates))
{
    echo "Dates are within range";
}   
else
{
    echo "Dates are NOT within range";
}   
like image 31
Will Johnson Avatar answered Oct 30 '22 10:10

Will Johnson


$start = strtorime($contract_start_date);
$end = strtotime($contract_end_date);

$required_start = strtotime("2011-05-05");
$required_end = strtotime("2011-10-10");

if ($end > $required_end or $end < $required_start)
{
  //out of range
}

if ($start < $required_start or $start > $required_end)
{
  //out of range
}
like image 29
genesis Avatar answered Oct 30 '22 10:10

genesis