SQL Server - Time difference in HH hours, MM minutes and SS seconds format‏

Suppose you have two datetime values and want to express the difference in the format HH Hours, MM minutes and SS seconds. You can use CONVERT function with style 108 as shown below:

declare @start_date datetime, @end_date datetime
select @start_date ='20121210 11:19:33', @end_date='20121210 19:28:12'      


select stuff(stuff(convert(varchar(10),@end_date-@start_date,108),6,1,' Minutes and '),3,1,' Hours, ')+' Seconds'


The variables @start_date and @end_date have values for start and end times. We can directly substract @start_date from @end_date and the result is still in datetime. CONVERT with style 108 will only extract time part in the format HH:MM:SS.

Now replace : after HH with Hours, replace : after MM with minutes and , append ' Seconds' at the end of time and the result is at the format HH Hours, MM minutes and SS seconds.

The result of the above code is

08 Hours, 08 Minutes and 39 Seconds

No comments:

Post a Comment