DATEDIFF() – Time Related Functions

I am constant in my creation of short articles or tidbits on Transaction SQL date/time functions.

Most, if not all, modern day computer systems collect data which contains dates and times. Many times you will want to calculate the difference between two given dates using a particular unit of measure (date part) like hours, minutes, or seconds.

Today, I will be exploring the DATEDIFF() function. This function has 12 different input parameters that can be passed to change the resulting output.

To summarize, the function takes a date part, a start date/time variable and a end date/time variable as input returns the calculated difference in the correct unit of measure.

I will be exploring the three time part parameters that determine the units of measure

DATE PART PARAMETER TO USE
HOUR HH
MINUTE MI or N
SECOND SS or S

 

The examples below are sample calls to the function. The inputs puts are valid date part parameters and date time variables.

The output from the test is listed below.

Like any good unit test, one should try both positive and negative test cases. I am not going to explore how an EMPTY string or NULL value effect the results provided by the function.

However, the following rules apply. Any invalid date parameter results in a raised error. Any NULL values passed as parameters result in a NULL result. Any EMPTY strings result in a default date.

To make a long story short, pass one of the three date part parameters (time) with two date/time variables to calculated the difference. Next time, I will be talking about how to use this function with Sub-Second related Parts.

Related posts

Leave a Comment