views:

41

answers:

1

I just tried to insert two rows with the current datetime and then calculated the elapsed time since that date. Here are the rows from my table after two insertions and using NOW() function to set the timestamp:

mysql> select * from pendingActivations;
+--------+------------+---------------------+
| userId | code       | timestamp           |
+--------+------------+---------------------+
|      2 | aaa        | 2010-08-23 17:04:02 |
|   2345 | alkfjkla23 | 2010-08-23 16:59:53 |
+--------+------------+---------------------+

Few minutes after the insertion of the row with userId equal to 2, I executed the following command which I hoped would give me the elapsed time from the timestamp for each row. Here are the results:

mysql> select userId, code, timestamp, NOW() - timestamp as elapsedSeconds from pendingActivations;
+--------+------------+---------------------+----------------+
| userId | code       | timestamp           | elapsedSeconds |
+--------+------------+---------------------+----------------+
|      2 | aaa        | 2010-08-23 17:04:02 |     136.000000 |
|   2345 | alkfjkla23 | 2010-08-23 16:59:53 |    4585.000000 |
+--------+------------+---------------------+----------------+

I wonder how the second row has that huge elapsedSeconds value which indicates that exactly 1 hour, 16 minutes and 25 seconds had passed, although it is easily seen that just around 5 minutes had passed since.

Here is the table structure:

mysql> describe pendingActivations;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| userId    | int(11)     | NO   | PRI | NULL    |       | 
| code      | varchar(32) | NO   | UNI | NULL    |       | 
| timestamp | datetime    | NO   |     | NULL    |       | 
+-----------+-------------+------+-----+---------+-------+

Any ideas and/or explanations?

+2  A: 

I can't explain the issue, but I suspect the - operation returns the result in an unexpected format (maybe including microseconds or tenths?)

I would use TIMEDIFF().

returns expr1expr2 expressed as a time value. expr1 and expr2 are time or date-and-time expressions, but both must be of the same type.

Pekka
+1 I agree with the recommendation to use TIMEDIFF. The explanation is that MySQL treats the values as numeric values in the format yyyyMMddHHmmss then does the subtraction on those numeric values.
Mark Byers