您可以使用类似于下面的代码来生成数据。几个月的时间不是很精确,因为我一个月用了 30 天。多年来,我每年使用 365 天。但我想这应该足够精确。
declare @date1 as datetime = '20131103 13:00:40'
declare @date2 as datetime = '20160208 16:40:45'
select case
when datediff(ss, @date1, @date2) < 60 THEN cast(datediff(ss, @date1, @date2) as varchar(max)) + ' seconds ago'
when datediff(ss, @date1, @date2) < 3600 THEN cast((datediff(ss, @date1, @date2) / 60) as varchar(max)) + ' minutes ago'
when datediff(ss, @date1, @date2) < 86400 THEN cast((datediff(ss, @date1, @date2) / 3600) as varchar(max)) + ' hours ago'
when datediff(ss, @date1, @date2) < 2592000 THEN cast((datediff(ss, @date1, @date2) / 86400) as varchar(max)) + ' days ago'
when datediff(ss, @date1, @date2) < 31536000 THEN cast((datediff(ss, @date1, @date2) / 2592000) as varchar(max)) + ' months ago'
else cast((datediff(ss, @date1, @date2) / 31536000) as varchar(max)) + ' years ago'
end
查询中的数字来自秒数:
- 分钟 = 60
- 小时 = 3600
- 天 = 86400
- 月 = 2592000
- 年 = 31536000
不只使用几秒钟的更简单的版本是:
declare @date1 as datetime = '20131003 13:00:40'
declare @date2 as datetime = '20151101 16:40:45'
select case
when datediff(ss, @date1, @date2) < 60 THEN cast(datediff(ss, @date1, @date2) as varchar(max)) + ' seconds ago'
when datediff(mi, @date1, @date2) < 60 THEN cast((datediff(mi, @date1, @date2)) as varchar(max)) + ' minutes ago'
when datediff(hh, @date1, @date2) < 24 THEN cast((datediff(hh, @date1, @date2)) as varchar(max)) + ' hours ago'
when datediff(dd, @date1, @date2) < 30 THEN cast((datediff(dd, @date1, @date2)) as varchar(max)) + ' days ago'
when datediff(mm, @date1, @date2) < 13 THEN cast((datediff(mm, @date1, @date2)) as varchar(max)) + ' months ago'
else cast((datediff(yy, @date1, @date2)) as varchar(max)) + ' years ago'
end