DateTime to "Friendly" Date


Written on Monday, September 08, 2008 by
I really like it when an application presents dates in a friendly "n Hours Ago" format. Mostly because I'm lazy and hate to do extra brain-work. John Resig created "pretty date" and it's insanely useful. It also plugs into JQuery very easily. But on the project I am working on it made more sense to provide this functionality within the database. So I created a pretty date function for SQL. [sourcecode language="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 [/sourcecode]
Back

Let's talk about this

 


The opinions expressed herein are my own and do not represent my employer's view in any way.


Creative Commons License