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

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

    As you say, I probably wouldn't do it in SQL, but as a thought exercise have a MySQL implementation:

    CASE
        WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now() 
            THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago')
    
        WHEN datediff(now(), compare_date) = 1 
            THEN 'Yesterday'
    
        WHEN compare_date between date_sub(now(), INTERVAL 24 hour) and now() 
            THEN concat(hour(TIMEDIFF(NOW(), compare_date)), ' hours ago')
    
        ELSE concat(datediff(now(), compare_date),' days ago')
    END
    

    Based on a similar sample seen on the MySQL Date and Time manual pages

提交回复
热议问题