Explain Codes LogoExplain Codes Logo

How to get the difference between two dates rounded to hours

sql
date-functions
time-difference
sql-queries
Alex KataevbyAlex Kataev·Oct 7, 2024
TLDR

Find the hour difference instantly:

SELECT TIMESTAMPDIFF(HOUR, 'StartDateTime', 'EndDateTime') AS HoursDifference

Just replace 'StartDateTime' and 'EndDateTime' with your real datetime values to get the rounded hour difference.

Calculating time with precision

For more detail that includes minutes as decimals:

SELECT TIME_TO_SEC(TIMEDIFF('EndDateTime', 'StartDateTime')) / 3600 AS DecimalHoursDifference -- You must divide by 3600. Because 60sec*60min = 3600 sec! Yeah, math!

Including all time elements

To showcase full time details:

SELECT TIME_FORMAT(SEC_TO_TIME(TIMESTAMPDIFF(SECOND, 'StartDateTime', 'EndDateTime')), '%H hours, %i minutes and %s seconds') AS FormattedTimeDifference -- Because Time waits for no one! ⌛

This paints your time difference with hours, minutes, and seconds.

Catering to specific time elements

To pinpoint the exact minutes and seconds:

SELECT TIMESTAMPDIFF(MINUTE, 'StartDateTime', 'EndDateTime') AS MinutesDifference, TIMESTAMPDIFF(SECOND, 'StartDateTime', 'EndDateTime') AS SecondsDifference -- Who said time can't be fractioned? Certainly not this SQL query!

Displaying time in human language

Turn the time difference into a friendly format:

SELECT CONCAT( FLOOR(TIMESTAMPDIFF(MINUTE, 'StartDateTime', 'EndDateTime') / 60), ' hours and ', MOD(TIMESTAMPDIFF(MINUTE, 'StartDateTime', 'EndDateTime'), 60), ' minutes' ) AS ReadableTimeDifference -- Because digital time is "so last millisecond" 🕰

This makes it clear and easy to interpret.

Tackling edge cases

When diving into date and time functions, keep these points in mind:

  • Time zones: Use the CONVERT_TZ function to adjust dates between time zones.
  • Daylight saving: Changes due to daylight saving can impact calculations.
  • Leap seconds: Rare but may introduce discrepancies. SQL fails to factor this, but don't forget!