淡季时间计算

时间:2013-01-14 16:09:46

标签: php mysql

我不知道“淡季”或“死”是否是我问题中的正确定义。无论如何,这是解释:

我的数组中有$period['from']$period['to'],我需要计算2013年的“死亡或淡季”时段。

输入期间示例:

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

和死区将是(输出):

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

我完全坚持这个。 任何帮助将不胜感激,

卡尔斯

1 个答案:

答案 0 :(得分:2)

试试这个:

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));

这将产生:

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 ) 
)