Only show hours in MYSQL DATEDIFF
In MySQL, hourly differences between timestamps is most accurately counted with TIMESTAMPDIFF
and HOUR
:
This will return the full hour count between start_time
and end_time
. Now, this might work on the starship Enterprise but here on earth, we avoid using DATEDIFF
for hours, since it views everything in days.
Precision-first approach
Precision is paramount when dealing with time, these points ensure that your calculations are on the dot:
Leveraging UNIX_TIMESTAMP
Another way to get the hour difference is subtracting UNIX_TIMESTAMP
values and dividing the result by 3600:
Note: UNIX_TIMESTAMP
returns time as UNIX timestamp, which are seconds since the '1970-01-01 00:00:00' UTC.
Beware the Ides of Midnight
When start_time
and end_time
spans past midnight, TIMEDIFF
returns negative hours:
The -
sign means start_time
is larger than end_time
. To avoid such spooky results, always feed the later timestamp as end_time
.
Tunnel vision focus on precision
When it comes to time, the difference of a moment is all that matters. Let's dive deeper into nuances:
Handling Date Boundary with TIMESTAMPDIFF and TIMEDIFF
The solution to time difference insensitivity towards date boundary is to use TIMESTAMPDIFF
. It returns the hour difference as an integer, irrespective of the date boundary.
So unlike TIMEDIFF
, TIMESTAMPDIFF
isn't afraid of crossing that date boundary!
TIMEDIFF: Minute Precision Maestro
For short periods that do not cross date boundaries, TIMEDIFF
followed by HOUR()
is more suitable:
Note: Keep an eye for negative results, TIMEDIFF
is sensitive
Tricky time caveats to remember
Time is simple until it isn't, let's explore some oft-forgotten fuse-blowers:
Time Zone and Daylight Saving Time
Beware of the time zone nuances and daylight saving time, they can throw your calculations off balance.
Leap Seconds
While leap seconds don't often show up at parties, when they do, they come uninvited. MySQL does not consider leap seconds, be aware when precision is key.
Overflow and Underflow
“Always expect the unexpected” and plan for potential overflow or underflow. Be cautious when the result exceeds a typical integer or decimal data type range.
Was this article helpful?