Youngnate DaGreat
Youngnate DaGreat

Reputation: 322

Compare a DateTime object against another in PHP 5.3

Okay, so I'm making an online text-based game, and I'm stuck right now with an on completion:

function....

    // I can't get this script to execute when I know the time has passed.

    $now = new DateTime("now", new DateTimeZone('UTC'));
    $row_date = new DateTime($row["due_date"], new DateTimeZone('UTC'));

    if ($row_date->format('Y-m-d H:i:s') <= $now->format('Y-m-d H:i:s')) 
    {
        mysql_query(".....")VALUES ("....")or die(mysql_error());
        mysql_query("DELETE FROM ......")or die(mysql_error());
    }
    else 
    {
        // The time has not come yet.
    }

This code is to be executed every 10 seconds with jQuery's setInterval.

Upvotes: 1

Views: 5048

Answers (3)

anubhava
anubhava

Reputation: 785098

You can avoid converting to DateTime class and use seconds since Epoch value to do any date comparison. Your code would be like this:

date_default_timezone_set('UTC');
$row_date = strtotime($row["due_date"]);
if ($row_date <= time()) { // The time has come
    mysql_query(".....") VALUES ("....") or die(mysql_error());
    mysql_query("DELETE FROM ......") or die(mysql_error());
}
else {
    // The time has not come yet.
}

Upvotes: 1

Adam Fowler
Adam Fowler

Reputation: 1751

Convert it into a unix timestamp. Perfect for whatever your needs are. You can use timestamps to sort time easily, and figure out what event comes first.

$ts=strtotime($date);

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 131871

DateTime is compareable

if ($row_date <= new DateTime) { /* Do something */ }

Upvotes: 11

Related Questions