Skip to content

Instantly share code, notes, and snippets.

@LSTANCZYK
Last active October 12, 2018 22:50
Show Gist options
  • Save LSTANCZYK/a39fa7cf38dac2857cfc6bfa4d331f23 to your computer and use it in GitHub Desktop.
Save LSTANCZYK/a39fa7cf38dac2857cfc6bfa4d331f23 to your computer and use it in GitHub Desktop.
Humanize Date SQL Function
SELECT dbo.humanizeDate(getdate()-1.56)
SELECT dbo.humanizeDate(getdate()-1)
SELECT dbo.humanizeDate(getdate()-.56)
SELECT dbo.humanizeDate(getdate()+22.56)
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION HumanizeDate
(
@timestamp AS datetime
)
RETURNS varchar(max)
AS
BEGIN
DECLARE @result as Varchar(max)
DECLARE @now AS datetime= getdate()
SELECT @result=
CONVERT(VARCHAR(40), abs(DATEDIFF(minute, @timestamp, @now)/(24*60)))+ ' days, '
+ CONVERT(VARCHAR(40), abs(DATEDIFF(minute, @timestamp, @now)%(24*60)/60)) + ' hours, and '
+ CONVERT(VARCHAR(40), abs(DATEDIFF(minute, @timestamp, @now)%60))+ ' minutes '
+ CASE WHEN @timestamp<=@now THEN 'ago' ELSE 'from now' end
set @result = Replace(@result,'1 days','1 day')
set @result = Replace(@result,'1 hours','1 hour')
set @result = Replace(@result,'1 minutes','1 minute')
set @result = Replace(@result,'0 days, ','')
set @result = Replace(@result,', and 0 minutes','')
set @result = Replace(@result,', 0 hours','')
RETURN isnull(@result,'never')
END
GO
USE dba
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION HumanizeDurationInMinutes
(
@minutes AS int
)
RETURNS varchar (max)
AS
BEGIN
DECLARE @ResultVar nvarchar(max)
SELECT @ResultVar = CAST(CAST((SUM(@minutes)) AS INT) / 60 AS VARCHAR)
+' hr '+
RIGHT('0'+CAST(CAST((SUM(@minutes)) AS INT) % 60 AS VARCHAR(2)), 2)+' min'
-- Return the result of the function
RETURN @ResultVar
END
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment