If Statement with date

☆樱花仙子☆ 提交于 2019-12-11 19:09:34

问题


I am doing an assignment for school, and I get bonus marks if I add a discount on a certain day. I have an actively updating time, using the date function(is it a function?) but I don't know how I would go about making an if statement for this.

Here is my code:

<?php
    $t = time();
    echo "Date of Purchase: " . (date("Y-m-d", $t));

    if(date == "20140224") {
        echo $b;
        echo "It works!";
    }
?>

Obviously I only provided relevant code. Any help is appreciated!


回答1:


Use DateTime() as DateTime objects are comparable:

$today = new DateTime();
$discountDate = new DateTime('2014-02-24');
if ($today == $discountDate) {
   // today is discount day!
}

Tip: No need to use time() to pass a second parameter to date(). date() always assumes "now" when no second parameter is passed




回答2:


This is untested, but the idea is that you have a function with parameters.

function getPrice($price, $search_date, $happyDays=5) {

    if(date('w', strtotime($search_date)) == $happyDays) {
      return $price * 0.8; // 20% discount
    } else {
      return $price; // full price
    }

}

Call it like so:

echo "Sum: " . getPrice(100, $_SESSION['purchase_date']);

Ps. I use a session date value, since I think the customer should get the discount if he/she places the order just before midnight :-) (as long as the session is still alive).



来源:https://stackoverflow.com/questions/21999879/if-statement-with-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!