0

有没有人看过任何自定义代码示例来确定两个日期之间的明显差异。即类似于脸书上的。

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

2 回答 2

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
于 2012-11-28T10:02:23.707 回答
0

感谢您的帮助,在这种情况下,我认为它太复杂并且无法在 SQL 中很好地实现,此外,客户端逻辑会更有效,因为我打算使用 jQuery 来更新这些值 ala facecrack。

发现这个库非常适合我的目的。

于 2012-11-28T13:26:37.820 回答