工作日和周末的价格不同

时间:2016-05-02 18:31:21

标签: php mysql

我有一张表订单,其中包含有关租车日期范围和汽车租赁价格的信息。

Table Orders

Table Cars

价格由:

给出
SELECT ROUND((points * (SELECT DATEDIFF('$dateTo', '$dateFrom'))) * 0.95) AS price

$dateTo$dateFrom是PHP变量,用于保存给定日期范围的值。换句话说:

$dateTo = $_POST['date-to'];
$dateFrom = $_POST['date-from'];

因此,每天您可以从租赁价格中获得5%的折扣,但我还想查看日期范围是否在周六或周日。如果租金是从周五到周一,我想在总价中加10点,因为日期范围包括星期六。

这可能吗?

1 个答案:

答案 0 :(得分:0)

您可以将存储过程用于此目的,其中您的查询可以嵌套在循环内以检查它是否是工作日。 或者,您可以使用PHP检查日期范围是否有周末:

<?php 

    /**
     * FUNCTION THAT CHECKS IF A WEEKEND EXISTS BETWEEN 2 GIVEN DATES
     * @param string $startDate 
     * @param string $endDate 
     * @return boolean
     */
    function dateRangeContainsWeekend($startDate, $endDate) {
        $tsDate  = strtotime($startDate);
        $diff    = date_diff(date_create($startDate), date_create($endDate));
        $dDiff   = $diff->days;

        if ($dDiff > 0) {
            for ($i = 0; $i < $dDiff; $i++) {
                $timeDiff  = 24 * 60 * 60 * $i;
                $sDate     = $tsDate + $timeDiff;
                $weekDay   = date('w', $sDate);

                if (($weekDay == 0 || $weekDay == 6)) {
                    return ($weekDay == 0 || $weekDay == 6);
                }
            }
        }
        return false;
    }

    // TESTS - - - -
    $d1 = "2016-05-02";
    $d2 = "2016-05-10";
    var_dump( dateRangeContainsWeekend($d1, $d2) );  // DUMPS true

    // NOW; IF YOU KNOW THAT THE GIVEN DATES CONTAIN A WEEKEND,
    // YOU MAY MODIFY YOUR QUERY TO REFLECT YOUR DESIRES 
    $factor = "0.95";  //CHOOSE YOUR FACTOR HERE...
    $sql    = "SELECT ROUND((points * (SELECT DATEDIFF('$dateTo', '$dateFrom'))) * $factor) AS price";