Get the difference between two datetimes



--get the difference between two datetimes in the format: 'h:m:s'
CREATE FUNCTION [dbo].[ufn_utl_getDateDiff]
(
    @startDate DATETIME
  , @endDate DATETIME
)
RETURNS VARCHAR(10)

-- =============================================
-- Author: Mihir Shah (UHC\mshah1)
-- Create date: 4/09/2018
-- Purpose: Purpose of this function is calculate Date differance between 2 dates
-- Usage:
--DECLARE @StartDate DATETIME = '10/01/2012 08:40:18.000'
--DECLARE @endDate DATETIME = '10/04/2012 09:52:48.000'
--SELECT dbo.ufn_utl_getDateDiff(@startDate, @endDate) AS DateDifference
-- Output:
-- =============================================

AS
BEGIN
    DECLARE @seconds INT = DATEDIFF(s, CONVERT(DATETIME, @startDate), CONVERT(DATETIME, @endDate));
    DECLARE @difference VARCHAR(10) = CONVERT(VARCHAR(4), @seconds / 3600) + ':'
                                      + CONVERT(VARCHAR(2), @seconds % 3600 / 60) + ':'
                                      + CONVERT(VARCHAR(2), @seconds % 60);
    RETURN @difference;
END;

GO


Comments

Popular posts from this blog

Calculating Age of the person in T-SQL

How to Troubleshoot Subscription issue in Reporting Services

MDX Queries - Current Day - Month and Year