0

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!

4
  • Can you show some actual values? The difference is likely to be time zones Commented Feb 14, 2011 at 19:42
  • I would suggest using timestamps in your database, but thats just me. Also, it doesn't matter if the user changes their time on their machine because time() is called from the machine that the script is hosted on. On the other hand, if the machines time is changed, then you are risking time mismatching. Commented Feb 14, 2011 at 19:43
  • In almost all cases, asking "what if the user changes the time on their computer?" shows a good deal of overengineering. Commented Feb 14, 2011 at 19:44
  • If you are on PHP 5.3, does date_parse_from_format('Y-m-d H:i:s', $date_time_from_db) give you the correct time? Commented Feb 14, 2011 at 19:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I was hoping that I could do this without going to the database but this will work. Thank you!
Well, your variable name suggests you're using a database to get some data to begin with. But if your query's actually fetching only a single date/time value, then have the DB convert it to a unix_timestamp (a simple signed 32bit integer) first, which is also PHP's native internal time representation
I just tested this and it works perfect! Thank you so much! Yes, I was already getting the data from the db so I just added to the select statement NOW() as CurrentTime and it works down to the second.
Yeah. MySQL's got now() for date+time, and curdate() and curtime() for just the date and time components

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.