Karls
Karls

Reputation: 93

off-season time period calculation

I don't know if the "off-season" or "dead" is the correct definition in my question. Anyway, here is the explanation:

Having $period['from'] and $period['to'] in my array, i need to calculate the "dead or off-season" periods in the year 2013.

Example input periods:

From            To
2013-04-01      2013-06-01
2013-07-15      2013-07-20
2013-09-01      2013-10-31

and the dead-periods will be (output):

From            To
2013-01-01      2013-03-31
2013-06-02      2013-07-14
2013-07-21      2013-08-31
2013-11-10      2013-12-31

I am totally stuck with this. Any help would be appreciated,

Karls

Upvotes: 1

Views: 146

Answers (1)

Jakub Truneček
Jakub Truneček

Reputation: 8990

Try this:

function dateDiff(array $dates, $startAt = null, $endAt = null) {
    if ($startAt === null) {
        $startAt = date("Y-01-01");
        $start = strtotime($startAt) - 86400;
    } else {
        $start = strtotime($startAt);
    }        

    if ($endAt === null) {
      $endAt = date("Y-12-31");
    }

    $result = array();

    foreach ($dates as $row) {
        $to = strtotime($row['from']);      
        $result[] = array('from' => date('Y-m-d', $start + 86400), 'to' => date('Y-m-d', $to - 86400));
        $start = strtotime($row['to']);;
    }
    $result[] = array('from' => date('Y-m-d', $start + 86400), 'to' => date('Y-m-d', strtotime($endAt)));

    return $result;
}



$dates = array(
    array('from' => '2013-04-01', 'to' => '2013-06-01'),
    array('from' => '2013-07-15', 'to' => '2013-07-20'),
    array('from' => '2013-09-01', 'to' => '2013-10-31'),
);

print_r(dateDiff($dates));

This will produce:

Array ( 
    [0] => Array ( [from] => 2013-01-01 [to] => 2013-03-31 ) 
    [1] => Array ( [from] => 2013-06-02 [to] => 2013-07-14 ) 
    [2] => Array ( [from] => 2013-07-21 [to] => 2013-08-31 ) 
    [3] => Array ( [from] => 2013-11-01 [to] => 2013-12-31 ) 
)

Upvotes: 2

Related Questions