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

About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

No comments: