PHP日期&一天数

时间:2012-03-28 11:35:14

标签: php date

我有一个场景,用户提交酒店预订的开始和结束日期。该数据库具有一年中不同的(每日)价格。鉴于用户的日期范围,我想首先计算用户范围在数据库的每个范围内的天数,然后乘以该日期范围的每日价格。

用户的日期:

  03 Jun 2012 - 03 Jul 2012

相关日期范围来自数据库

Array
(
    [0] => stdClass Object
        (
            [date_from] => 2012-04-09
            [date_to] => 2012-06-04
            [price] => 44
        )

    [1] => stdClass Object
        (
            [date_from] => 2012-06-04
            [date_to] => 2012-07-02
            [price] => 52
        )

    [2] => stdClass Object
        (
            [date_from] => 2012-07-02
            [date_to] => 2012-07-16
            [price] => 61
        )

)

如您所见,预订从第一个范围开始,跨越第二个范围并以第三个范围结束。

foreach ($dates as $key => $d)
{
    $days = 0;

    $user_start = strtotime($range['start']);
    $user_stop = strtotime($range['stop']);
    $db_start = strtotime($d->date_from);
    $db_stop = strtotime($d->date_to);

    if( $user_start >= $db_start && $user_stop < $db_stop )
    {
        $start = $range['start'];
        $stop = $range['stop'];
    }

    elseif( $user_start <= $db_start && $user_stop > $db_start )
    {
        $start = $d->date_from;
        $stop = $d->date_to;
    }    

    elseif( $user_start <= $db_stop && $user_stop > $db_stop )
    {
        $start = $range['start'];
        $stop = $d->date_to;
    }

    $days = calculate_nbr_days($start, $stop);

    $price += $days * $d->price;
}

此代码几乎可以正常工作,除了它将预留结束($stop)作为DB范围的最后日期而不是用户的范围,我无法弄清楚为什么!< / p>

1 个答案:

答案 0 :(得分:2)

您是否考虑过在SQL中完成所有操作?这应该有用:

SELECT
  SUM(
    datediff(
      IF($dateTo>date_to,date_to,$dateTo),
      IF($dateFrom<date_from,date_from,$dateFrom)
    ) * price_per_day
  ) as total_cost
FROM ranges
WHERE '$dateFrom'<=date_to
  AND '$dateTo'>=date_from