Here’s a complication of some common and useful time & date calculations and equations. Some, though very simple, are often misunderstood, leading to inefficient or incorrect implementations.
There are many ways to solve such problems. I’ll present my favorites.
Querying for time difference
Given two timestamps: ts1 (older) and ts2 (newer), how much time has passed between them?
One can use TIMEDIFF() & DATEDIFF(), or compare two UNIX_TIMESTAMP() values. My personal favorite is to use TIMESTAMPDIFF(). Reason being that I’m usually interested in a specific metric, like the number of hours which have passed, or the number of days, disregarding the smaller minute/second resolution. Which allows one to:
SELECT TIMESTAMPDIFF(HOUR, ts1, ts2)
Take, for example:
SELECT TIMESTAMPDIFF(MONTH, '2008-10-07 00:00:00', '2009-12-06 00:00:00')
The function correctly identifies the number of days per month, and provides with 13, being the truncated number of full months.
Doing arithmetics
One can use TIMESTAMPADD(), or DATE_SUB(), but, again, when dealing with specific resolutions, I find “+ INTERVAL” to be the most convenient:
SELECT ts1 + INTERVAL 10 HOUR