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

前端 未结 7 1877
醉酒成梦
醉酒成梦 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条回答
  •  旧时难觅i
    2021-01-18 04:03

    How about this? You could expand this pattern to do "years" messages, and you could put in a check for "1 day" or "1 hour" so it wouldn't say "1 days ago"...

    I like the CASE statement in SQL.

    drop function dbo.time_diff_message    
    GO
    
    create function dbo.time_diff_message (
        @input_date datetime
    )
    returns varchar(200)    
    as    
    begin    
    declare @msg varchar(200)    
    declare @hourdiff int
    
    set @hourdiff = datediff(hour, @input_date, getdate())    
    set @msg = case when @hourdiff < 0 then ' from now' else ' ago' end    
    set @hourdiff = abs(@hourdiff)    
    set @msg = case when @hourdiff > 24 then convert(varchar, @hourdiff/24) + ' days' + @msg
                    else convert(varchar, @hourdiff) + ' hours' + @msg
                end
    
    return @msg
    end
    
    GO    
    select dbo.time_diff_message('Dec 7 1941')
    

提交回复
热议问题