Domanda

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!

È stato utile?

Soluzione

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

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top