dtntcdr
dtntcdr

Reputation: 3

PHP Compare Datetime

I have the following problem. I am trying to compare two datetime values in PHP but the calculation is invalid. There is about 8 hours of difference. I am on my development machine using WAMPServer

if(strtotime($date_time_from_db) < time())
{
    // do something
}

The datetime value in the database is in the following format: Y-m-d H:i:s. How can I do this accurately? Also, is using time() a good idea? What happens if the user changes the time on their machine?

Thanks very much!

Upvotes: 0

Views: 2178

Answers (1)

Marc B
Marc B

Reputation: 360672

Don't do date/time comparisons in PHP if you're pulling those values from a database. That involves a double round-trip of conversions: date/time -> text -> date-time. You can do the exact same thing at the database level:

SELECT ...
FROM table
WHERE datetimefield < now()

which allows use of indexes (good) and eliminates two type conversions (also good).

As for user changing time - well, that's just the user's machine. Unless you're doing this as part of an app for sale, then the user has absolutely no way of affecting the time on your database server.

Upvotes: 2

Related Questions