SQL Server

How to get Time Ago From SQL

DECLARE @GivenDate DATETIME;
DECLARE @CrrDate DATETIME;

SET @GivenDate = '2017-12-17 14:01:00.000';
SET @CrrDate = GETDATE();

DECLARE @YEARS INT,@MONTH INT,@WEEKS INT ,@DAYS INT, @HOURS INT, @MINUTES INT, @SECONDS INT, @DATE NVARCHAR (500)

SET @YEARS = DATEDIFF(second, @GivenDate, @CrrDate) / 60 / 60 / 24 / 7 / 4 / 12 -- FOR YEAR
SET @MONTH = DATEDIFF(second, @GivenDate, @CrrDate) / 60 / 60 / 24 / 7 / 4 -- FOR MONTH
SET @WEEKS = DATEDIFF(second, @GivenDate, @CrrDate) / 60 / 60 / 24 / 7 -- FOR WEEK
SET @DAYS  = DATEDIFF(second, @GivenDate, @CrrDate) / 60 / 60 / 24 -- FOR DAY
SET @HOURS = DATEDIFF(second, @GivenDate, @CrrDate) / 60 / 60 % 24 -- FOR HOURS
SET @MINUTES = DATEDIFF(second, @GivenDate, @CrrDate) / 60 % 60 -- FOR MINUTES
SET @SECONDS = DATEDIFF(second, @GivenDate, @CrrDate) % 60 -- FOR SECONDS

IF (@YEARS > 0)
BEGIN
    SET @DATE = CONVERT(VARCHAR(50),@YEARS) + 'y'
END

ELSE IF (@MONTH > 0)
BEGIN
    SET @DATE = CONVERT(VARCHAR(50),@MONTH) + 'mo'
END

ELSE IF (@WEEKS > 0)
BEGIN
    SET @DATE = CONVERT(VARCHAR(50),@WEEKS) + 'w'
END

ELSE IF (@DAYS > 0)
BEGIN
    SET @DATE = CONVERT(VARCHAR(50),@DAYS) + 'd'
END

ELSE IF (@HOURS > 0)
BEGIN
    SET @DATE = CONVERT(VARCHAR(50),@HOURS) + 'h '
    IF (@MINUTES > 0)
    BEGIN
        SET @DATE = @DATE + CONVERT(VARCHAR(50),@MINUTES) + 'm '
        IF (@SECONDS > 0)
        BEGIN
            SET @DATE = @DATE + CONVERT(VARCHAR(50),@SECONDS) + 's'
        END
    END
END

ELSE IF (@MINUTES > 0)
BEGIN
    SET @DATE = CONVERT(VARCHAR(50),@MINUTES) + 'm '
    IF (@SECONDS > 0)
    BEGIN
        SET @DATE = @DATE + CONVERT(VARCHAR(50),@SECONDS) + 's'
    END
END

ELSE IF (@SECONDS > 0)
BEGIN
    IF (@SECONDS > 10)
    BEGIN
        SET @DATE = CONVERT(VARCHAR(50),@SECONDS) + 's'
    END
    ELSE   
    BEGIN
        SET @DATE = 'Few Seconds'
    END
END

SELECT @DATE + ' ago'

2 comments :

  1. How to get date and time like(dd/mm/yyy HH:MM AM/PM) ??

    ReplyDelete
  2. SELECT CONVERT(VARCHAR(15),CAST(GETDATE() AS DATE),101) +' ' +CONVERT(VARCHAR(15),CAST(GETDATE() AS TIME),100)

    ReplyDelete