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

前端 未结 7 1911
醉酒成梦
醉酒成梦 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:05

    My attempt - this is for MS SQL. It supports 'ago' and 'from now', pluralization and it doesn't use rounding or datediff, but truncation -- datediff gives 1 month diff between 8/30 and 9/1 which is probably not what you want. Rounding gives 1 month diff between 9/1 and 9/16. Again, probably not what you want.

    CREATE FUNCTION dbo.GetFriendlyDateTimeValue( @CompareDate DATETIME ) RETURNS NVARCHAR(48) AS BEGIN
    declare @s nvarchar(48)
    set @s='Now'
    select top 1 @s=convert(nvarchar,abs(n))+' '+s+case when abs(n)>1 then 's' else '' end+case when n>0 then ' ago' else ' from now' end from (
     select convert(int,(convert(float,(getdate()-@comparedate))*n)) as n, s from (
      select 1/365 as n, 'Year' as s union all
      select 1/30, 'Month' union all
      select 1, 'Day' union all
      select 7, 'Week' union all
      select 24, 'Hour' union all
      select 24*60, 'Minute' union all
      select 24*60*60, 'Second'
     ) k
    ) j where abs(n)>0 order by abs(n)
    return @s
    END
    

提交回复
热议问题