I want to subtract between two date time values using SQL in MySQL such that I get the interval in minutes or seconds. Any ideas? I want to run a SQL query that retrieves uses from a database who have logged in like 10 minutes from the time.
views:
3990answers:
5
A:
You can try and cast them to Unix Time stamp, and take the difference.
Andrew Whittington
2009-06-11 14:03:58
+8
A:
There are functions TIMEDIFF(expr1,expr2), which returns the value of expr1-expr2, and TIME_TO_SEC(expr3), which expresses expr1 in seconds.
Note that expr1 and expr2 are datetime values, and expr3 is a time value only.
Check this link for more info.
Matthew Jones
2009-06-11 14:05:09
Thanks alot man - thats a lifesaver :)
Ali
2009-06-11 14:11:04
I've submit a more simple answer
David Caunt
2009-06-11 14:14:43
Why do you feel the need to point that out? If Ali likes your answer better, he should uncheck mine and mark yours. But there is no need for one-upmanship here; otherwise this community becomes about the reputation and not about the answers.
Matthew Jones
2009-06-11 14:17:19
@dcaunt All the answers are great and I appreciate all of them - I've marked Matthews post as the answer for the sole reason that its what I've chosen to implement :) thanks everybody for all the great help!
Ali
2009-06-11 15:46:54
@Matthew Jones - No hard feelings, I just thought that it was unnecessary to calculate a time difference if you don't need to know what the difference is and I felt my answer was clearer and easier to implement.
David Caunt
2009-06-12 09:51:47
Which is why I voted for you. :)
Matthew Jones
2009-06-12 13:28:11
+6
A:
TIMESTAMPDIFF is like TIMEDIFF which Matthew states, except it returns the difference of the two datetimes in whatever units you desire (seconds, minutes, hours, etc).
For example,
SELECT TIMESTAMPDIFF(MINUTE,LogOutTime,LogInTime) AS TimeLoggedIn
FROM LogTable
Would return the number of minutes the user was logged in (assuming you stored this kind of thing in a table like that).
Welbog
2009-06-11 14:08:08
Note that TIMEDIFF(expr1,expr2) results in expr1 - expr2, where TIMESTAMPDIFF(unit,expr1,expr2) results in expr2 - expr1. Just something to watch out for.
Matthew Jones
2009-06-11 14:09:45
+1
A:
I would do it like this - fetch where last activity is within 10 mins of now
SELECT * FROM `table` WHERE DATE_ADD(`last_activity`, INTERVAL 10 MINUTE) >= NOW()
David Caunt
2009-06-11 14:12:17