Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Logic, compare against specific date

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?

like image 896
John Bernal Avatar asked Sep 19 '26 05:09

John Bernal


1 Answers

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.

like image 175
Anirudh Ramanathan Avatar answered Sep 20 '26 20:09

Anirudh Ramanathan