自定义SQL datediff函数

时间:2012-11-28 08:29:14

标签: sql-server tsql datetime

有人看过任何自定义代码示例,用于确定两个日期之间的合理差异。即与Facebook上的相似。

  • 这是2秒前发布的
  • 这是昨天发布的
  • 这是4小时前发布的。

2 个答案:

答案 0 :(得分:2)

虽然同意在表示层可以做得更好,但这可以构成SQL解决方案的基础 - 如果你在SQL Server上需要它,你当然也可以用.Net语言编写一个CLR函数你的选择。

declare @d datetime = '2012-10-11 00:52'
select 
    case 
        when diff < 60 then convert(varchar(5), DATEDIFF(s, @d, getdate())) + ' seconds'
        when diff < 3600 then convert(varchar(5), DATEDIFF(MI, @d, getdate())) + ' minutes'
        when diff < 86400 then convert(varchar(5), DATEDIFF(hh, @d, getdate())) + ' hours'
        when diff < 604800 then convert(varchar(5), DATEDIFF(D, @d, getdate())) + ' days'
        when diff < 2419200 then convert(varchar(5), DATEDIFF(WEEK, @d, getdate())) + ' weeks'
        else convert(varchar(5), DATEDIFF(MONTH, @d, getdate())) + ' months'
    end
from
    (select DATEDIFF(s, @d, getdate()) as diff) v

答案 1 :(得分:0)

感谢您的帮助,在这种情况下,我认为它太复杂了,并且在SQL中很好地实现,增加了客户端逻辑将更高效的事实,因为我打算使用jQuery更新这些值ala facecrack。

Found this library which works perfectly for my purposes.