7

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 ?

2

4 Answers 4

9

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

1

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 />';
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.