BoqBoq
BoqBoq

Reputation: 4704

PHP Date Range Check

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 ?

Upvotes: 7

Views: 12018

Answers (4)

turbod
turbod

Reputation: 1988

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

Upvotes: 9

Sanjeev Chauhan
Sanjeev Chauhan

Reputation: 4097

Find below code to get date difference in days, month and year:

<?php
function datediff($date1,$date2,$format='d'){
    $difference = abs(strtotime($date2) - strtotime($date1));
    switch (strtolower($format)){
    case 'd':
        $days = round((($difference/60)/60)/24,0);
        break;
    case 'm':
        $days = round(((($difference/60)/60)/24)/30,0);
        break;
    case 'y':
        $days = round(((($difference/60)/60)/24)/365,0);
        break;
    }
    return $days;
}
//Example
echo datediff('2011-06-1','2010-8-30','D') . ' Days<br />'; 
echo datediff('2011-06-1','2010-8-30','m') . ' Months<br />'; 
echo datediff('2011-06-1','2010-8-30','y') . ' Years<br />';
?>

Upvotes: 1

Will Johnson
Will Johnson

Reputation: 225

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";
}   

Upvotes: 1

genesis
genesis

Reputation: 50966

$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
}

Upvotes: 2

Related Questions