Reputation: 140122
For example,how to calculate the interval between these two datetime:
2009-09-18 00:00:00
2009-10-17 00:00:00
EDIT
I mean to get the interval in the format of year-month-day hour:min:seconds
Upvotes: 12
Views: 26705
Reputation: 191
Or use timestampdiff() like this:
timestampdiff(microsecond,yourtime,now())
the first parameter is mysql datetime unit, can be "microsecond, second, minute, hour, day, year", and this function means the 3rd parameter datetime minus the 2nd parameter datetime.
mysql> select timestampdiff(second, "2009-09-18 00:00:00", "2009-10-17 00:00:00");
+---------------------------------------------------------------------+
| timestampdiff(second, "2009-09-18 00:00:00", "2009-10-17 00:00:00") |
+---------------------------------------------------------------------+
| 2505600 |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)
Upvotes: 6
Reputation: 401182
What about using datediff
:
mysql> select abs(datediff('2009-09-18 00:00:00', '2009-10-17 00:00:00'));
+-------------------------------------------------------------+
| abs(datediff('2009-09-18 00:00:00', '2009-10-17 00:00:00')) |
+-------------------------------------------------------------+
| 29 |
+-------------------------------------------------------------+
1 row in set (0.00 sec)
Quoting the manual :
DATEDIFF()
returnsexpr1 – expr2
expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions.
Only the date parts of the values are used in the calculation.
Upvotes: 14
Reputation: 7297
You can just subtract datetimes and it will return the value:
select (now() - interval 2 day) - (now() - interval 5 day);
The result isn't a datetime (it's some decimal coded date -- 3000000 for three days in this case), but it isn't correct to say consider a datetime and an interval as the same datatype.
Upvotes: 1