php-如果日期早于6个月前

时间:2019-02-07 19:11:36

标签: php date

我希望下面的代码检查客户的创建日期,如果他们已经有6个月了,那么价格会因为促销而上涨。我尝试下面的方法时并不高兴,我认为它只是使用月份而不考虑年份。例如,如果客户在9月上船,那么下个月的6个月将是第二年,并且永远不变。

谢谢

$created_date = date('m',strtotime($customer_order['created_at']));
            $current = date("m");

            $curmonth = date("m");

            $ordermonth = date("m",strtotime($udata['created_date']));
            $m_dff = $curmonth - $ordermonth;

            //print_r($m_dff."<br>");
            if($m_dff > 6){
                $unitcost = 19.99;

            }
            else{
                $unitcost = 14.99;
            }

3 个答案:

答案 0 :(得分:1)

strtotime()可以比您的示例更有效地使用,以下方法可以解决问题

if(time() > strtotime($customer_order['created_at'] . ' +6 months')) {
    $unitcost = 19.99;
} else {
    $unitcost = 14.99;
}

答案 1 :(得分:1)

$currentorder = date ('Y-m-d');
$createdaccount =  date('Y-m-d', strtotime("+6 months", 
strtotime($customer_order['created_at'])));

if($currentorder>=$createdaccount)
{
    $unitcost = 19.99;
}
else
{
    $unitcost = 14.99;
 }

答案 2 :(得分:0)

看看是否可以使用DateTime对象进行比较。

//set a general time zone at top of script
date_default_timezone_set('Europe/Amsterdam');

// if created_at is a valid dateTime string
$created = new \DateTime($customer_order['created_at']);

$current = new \DateTime();

$sixMonth = $created->add(new \DateInterval(‘P6M’));

if ($created < $current) {
    // if created + 6 months is older than current
    $price = 19.99;
} else {
    $price = 14.99;
}

有关更多信息,请参见:https://secure.php.net/manual/en/book.datetime.php