我编写了一个SQL函数来将SQL中的日期时间值转换为更友好的"n Hours Ago"或"n Days Ago"等类型的消息.我想知道是否有更好的方法来做到这一点.
(是的,我知道"不要在SQL中这样做",但出于设计原因,我必须这样做).
这是我写的函数:
CREATE FUNCTION dbo.GetFriendlyDateTimeValue ( @CompareDate DateTime ) RETURNS nvarchar(48) AS BEGIN DECLARE @Now DateTime DECLARE @Hours int DECLARE @Suff nvarchar(256) DECLARE @Found bit SET @Found = 0 SET @Now = getDate() SET @Hours = DATEDIFF(MI, @CompareDate, @Now)/60 IF @Hours <= 1 BEGIN SET @Suff = 'Just Now' SET @Found = 1 RETURN @Suff END IF @Hours < 24 BEGIN SET @Suff = ' Hours Ago' SET @Found = 1 END IF @Hours >= 8760 AND @Found = 0 BEGIN SET @Hours = @Hours / 8760 SET @Suff = ' Years Ago' SET @Found = 1 END IF @Hours >= 720 AND @Found = 0 BEGIN SET @Hours = @Hours / 720 SET @Suff = ' Months Ago' SET @Found = 1 END IF @Hours >= 168 AND @Found = 0 BEGIN SET @Hours = @Hours / 168 SET @Suff = ' Weeks Ago' SET @Found = 1 END IF @Hours >= 24 AND @Found = 0 BEGIN SET @Hours = @Hours / 24 SET @Suff = ' Days Ago' SET @Found = 1 END RETURN Convert(nvarchar, @Hours) + @Suff END
ConroyP.. 7
正如你所说,我可能不会在SQL中这样做,但是作为一个思考练习有一个MySQL实现:
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
基于在MySQL日期和时间手册页上看到的类似示例
正如你所说,我可能不会在SQL中这样做,但是作为一个思考练习有一个MySQL实现:
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
基于在MySQL日期和时间手册页上看到的类似示例