3

I need to write a php script that determines the amount the user has to pay depending on the date they register. The later they register the more they pay, so here's the basic code for the script:

private $date;

function __construct() {
    $this->date = getdate();
}

function get_amount()
{
    $day = $this->date["mday"];
    $month = $this->date["month"];
    $year = $this->date["year"];
    $date = $day.$month.$year;
    switch($date) {
        case "26October2012":
            return "800";
            break;
        case "26Novermber2012":
            return "900";
            break;
    }
}

But obviously this case statement doesn't work as it should. So if the user register before 26th October 2012 then they pay 800, if it's before 26th November but after 26th October then they pay 900. So how exactly do I code that logic?

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
John Bernal
  • 230
  • 5
  • 21

3 Answers3

4

Just convert your dates to a Unix Timestamp, compare them, to make the whole thing much simpler. Refer to the strtotime function.

$compare_date = "2012-10-26";
$todays_date = date("Y-m-d");

$today_ts = strtotime($todays_date);//unix timestamp value for today
$compare_ts = strtotime($compare_date);//unix timestamp value for the compare date

if ($today_ts > $compare_ts) {//condition to check which is greater
   //...
}

strtotime converts your date-time into a integer Unix Timestamp. Unix timestamp is defined as the number of seconds that have elapsed since midnight Coordinated Universal Time (UTC), 1 January 1970. So, being an integer, it is easy to compare, without string manipulation.

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • i don't understand what the strtotime does really. – John Bernal Oct 26 '12 at 06:17
  • It converts your date-time into a 32-bit integer [unix timestamp](http://en.wikipedia.org/wiki/Unix_time). Unix timestamp is defined as the number of seconds that have elapsed since midnight Coordinated Universal Time (UTC), 1 January 1970. So, being an integer, it is easy to compare, without string manipulation. – Anirudh Ramanathan Oct 26 '12 at 06:20
0

You cannot have a range comparison using a switch statement.

You can convert the dates to timestamps and then do the comparison using if-else.

codaddict
  • 445,704
  • 82
  • 492
  • 529
0

Create an array that contains amount for different dates:

$amountPerDate = array(
    '2012-10-26' => 800,
    '2012-11-26' => 900,
);

Loop thru it to get corresponding amount value:

krsort($amountPerDate); // Recursive sort to check greater dates first
$date = strtotime($date);  // Convert '2012-10-23' to its numeric equivalent for the date comprasion
$amount = 0; // Default amount value
foreach ($valuePerData as $date => $amount) {
    if ($date >= strtotime($date)) {
        $amount = $amount;
    }
}
Vadim Ashikhman
  • 9,851
  • 1
  • 35
  • 39