Tuesday 2 June 2015

PHP: Date range overlap check

<?php // Function to test for time overlap 
// $start_time    A start date YYYY-MM-DD HH:MM:SS 
// $end_time      An end date YYYY-MM-DD HH:MM:SS 
// $times         An array of times to match against 
// Returns true if there is an overlap false if no overlap is found 
function time_overlap($start_time$end_time$times){ 
    
$ustart strtotime($start_time); 
    
$uend   strtotime($end_time); 
    foreach(
$times as $time){ 
        
$start strtotime($time["start"]); 
        
$end   strtotime($time["end"]); 
        if(
$ustart <= $end && $uend >= $start){ 
            return 
true; 
        } 
    } 
    return 
false; 
} 
// A test list of times $list_of_times = array( 
    array( 
        
"start" => "2012-01-01 00:00:00", 
        
"end" => "2012-01-30 00:00:00" 
    
), 
    array( 
        
"start" => "2012-02-01 00:00:00", 
        
"end" => "2012-02-30 00:00:00" 
    
), 
    array( 
        
"start" => "2012-03-01 00:00:00", 
        
"end" => "2012-03-30 00:00:00" 
    
) 
); 
// Test some times if(!time_overlap("2012-03-15 00:00:00""2012-04-01 00:00:00"$list_of_times)){ 
    echo 
"No overlap found adding to array!<br />"; 
    
$list_of_times[]["start"] = "2012-03-15 00:00:00"; 
    
$list_of_times[]["end"] = "2012-04-01 00:00:00"; 
}else{ 
    echo 
"Overlap found time not added to array!<br />"; 
} 

if(!
time_overlap("2012-04-15 00:00:00""2012-05-01 00:00:00"$list_of_times)){ 
    echo 
"No overlap found adding to array!<br />"; 
    
$list_of_times[]["start"] = "2012-03-15 00:00:00"; 
    
$list_of_times[]["end"] = "2012-04-01 00:00:00"; 
}else{ 
    echo 
"Overlap found time not added to array!<br />"; 
}

0 comments:

Post a Comment