Best way to convert DateTime to “n Hours Ago” in SQL

前端 未结 7 1816
醉酒成梦
醉酒成梦 2021-01-18 03:52

I wrote a SQL function to convert a datetime value in SQL to a friendlier \"n Hours Ago\" or \"n Days Ago\" etc type of message. And I was wondering if there was a better wa

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 04:10

    The posts above gave me some good ideas so here is another function for anyone using SQL Server 2012.

        CREATE FUNCTION [dbo].[FN_TIME_ELAPSED] 
        (
            @TIMESTAMP DATETIME
        )
        RETURNS VARCHAR(50)
        AS
        BEGIN
    
        RETURN 
        (
            SELECT TIME_ELAPSED = 
                CASE
                    WHEN @TIMESTAMP IS NULL THEN NULL
                    WHEN MINUTES_AGO < 60 THEN CONCAT(MINUTES_AGO, ' minutes ago')
                    WHEN HOURS_AGO < 24 THEN CONCAT(HOURS_AGO, ' hours ago')
                    WHEN DAYS_AGO < 365 THEN CONCAT(DAYS_AGO, ' days ago')
                    ELSE CONCAT(YEARS_AGO, ' years ago') END
            FROM ( SELECT MINUTES_AGO = DATEDIFF(MINUTE, @TIMESTAMP, GETDATE()) ) TIMESPAN_MIN
            CROSS APPLY ( SELECT HOURS_AGO = DATEDIFF(HOUR, @TIMESTAMP, GETDATE()) ) TIMESPAN_HOUR
            CROSS APPLY ( SELECT DAYS_AGO = DATEDIFF(DAY, @TIMESTAMP, GETDATE()) ) TIMESPAN_DAY
            CROSS APPLY ( SELECT YEARS_AGO = DATEDIFF(YEAR, @TIMESTAMP, GETDATE()) ) TIMESPAN_YEAR
        )
        END
        GO
    

    And the implementation:

        SELECT TIME_ELAPSED = DBO.FN_TIME_ELAPSED(AUDIT_TIMESTAMP)
        FROM SOME_AUDIT_TABLE
    

提交回复
热议问题