Calculating difference between two mysql dates in seconds

Here is a quick way to calculate the difference between two mysql dates in number of seconds. In my case, i required to fetch all entries for which the difference between current time stamp and date in a table field would be less than 5 minutes.

SELECT TIME_TO_SEC(TIMEDIFF(now(), `last_active`)) as timediff FROM `users` where TIME_TO_SEC(TIMEDIFF(now(), `last_active`)) < 300

In the above example i do calculate difference between current time (now()) and date stored in the "last_active" field of my "users" table. TIMEDIFF function of MySQL calculates this difference in "hh:mm:ss" format and TIME_TO_SEC function of MySQL converts this difference into number of seconds.

This is how i did it. If someone knows of a better way to do it, please suggest. Thanks.

One thought on “Calculating difference between two mysql dates in seconds

Leave a Reply

Your email address will not be published. Required fields are marked *