Function to Display Difference Between Dates in Days, Hours, Minutes and Seconds in SQL Server
Hello to everyone,
In this article, I will try to give information about the function that displays the difference between dates as days, hours, minutes and seconds in SQL Server.
In SQL Server, in some cases, you may want to display the difference between dates in days, hours, minutes, and seconds.
You can easily do this using the function below.
CREATE FUNCTION dbo.ZamanFarkiBulanFonksiyon
(
@Tarih1 DATETIME,
@Tarih2 DATETIME
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @cikis VARCHAR(100);
DECLARE @saniye BIGINT;
SET @saniye =
(
SELECT DATEDIFF(SECOND, @Tarih1, @Tarih2)
);
SET @saniye = ISNULL(@saniye, 0);
SET @cikis = '0d 00:00:00';
IF (@saniye < 0)
RETURN @cikis;
SET @cikis = CONVERT(VARCHAR, FLOOR(@saniye / 86400)) + 'd ';
SET @saniye = @saniye % 86400;
SET @cikis = @cikis + RIGHT('0' + CONVERT(VARCHAR, FLOOR(@saniye / 3600)), 2) + ':';
SET @saniye = @saniye % 3600;
SET @cikis = @cikis + RIGHT('0' + CONVERT(VARCHAR, FLOOR(@saniye / 60)), 2) + ':';
SET @cikis = @cikis + RIGHT('0' + CONVERT(VARCHAR, @saniye % 60), 2); -------------
RETURN @cikis;
-------------
END;
--Çalıştırılması
SELECT dbo.ZamanFarkiBulanFonksiyon('2017-10-03 00:00:00', '2017-10-12 00:00:00');
SELECT dbo.ZamanFarkiBulanFonksiyon('2017-10-05 07:30:00', '2017-10-05 07:55:00');
SELECT dbo.ZamanFarkiBulanFonksiyon('2017-09-01 01:46:00', '2017-09-01 10:55:00');
SELECT dbo.ZamanFarkiBulanFonksiyon('2017-11-21 08:21:00', '2017-12-06 18:00:00');
When you create and run the above function, you will see a result similar to the one below.
As you can see, we have displayed the difference between dates as days, hours, minutes and seconds.
Good luck to everyone in business and life.