Strawberry
Strawberry

Reputation: 67968

Time comparison check against MySQL DATETIME stamp

I want to check if it has been an hour since the last datetime stamp in MySQL. How can I do this using PHP?

Upvotes: 3

Views: 2531

Answers (6)

futureal
futureal

Reputation: 3055

The cleanest way to do this is in MySQL using DATE_SUB (or DATE_ADD depending on your goals). For example:

SELECT DATE_SUB(NOW(), INTERVAL 1 HOUR)

Likewise you can replace "1 HOUR" with other things like "1 DAY" or "1 MINUTE" and so on. I always prefer to do date comparisons at the database level since presumably the dates are being stored in a common format and GMT offset.

Upvotes: 2

staticsan
staticsan

Reputation: 30575

You put the check into the query. Then you can use a MySQL date comparison and the PHP doesn't have to know or care.

Upvotes: 0

dqhendricks
dqhendricks

Reputation: 19251

you could and probably should do this entire thing in mysql instead

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

you can find the difference between a datetime field and the current time using your query, and return the result as a row.

Upvotes: 3

alex
alex

Reputation: 490647

$now = time();

$dbDate = strtotime($row['datetime']);

if ($now > $dbDate + 3600) {
   // yes
}

Upvotes: 0

Stephen
Stephen

Reputation: 18917

$db_time = strtotime($row->timestamp_col);
$age = 60 * 60;
if ($db_time < (time() - $age)) {
    doSomething();
}

This is unnecessarily broken down so you can see how it works.

Upvotes: 0

Ho&#224;ng Long
Ho&#224;ng Long

Reputation: 10848

This link explains about date_diff for PHP >= 5.3 and some work around solutions for older version.

Upvotes: 0

Related Questions