Following function calculates timeago from current time.
For ex.
2 hours 5 minutes ago
23 sec ago etc
Input:
Output:
For ex.
2 hours 5 minutes ago
23 sec ago etc
CREATE FUNCTION fn_relativeTime (@dateFrom DATETIME) RETURNS VARCHAR(100) AS BEGIN DECLARE @ret VARCHAR(100) DECLARE @dateTo DATETIME DECLARE @tmpdate DATETIME DECLARE @years INT DECLARE @months INT DECLARE @days INT DECLARE @hours INT DECLARE @minutes INT DECLARE @seconds INT DECLARE @milliseconds INT SELECT @dateTo = getdate() SELECT @tmpdate = @dateFrom SELECT @years = DATEDIFF(yy, @tmpdate, @dateTo) - CASE WHEN (MONTH(@dateFrom) > MONTH(@dateTo)) OR (MONTH(@dateFrom) = MONTH(@dateTo) AND DAY(@dateFrom) > DAY(@dateTo) ) THEN 1 ELSE 0 END SELECT @tmpdate = DATEADD(yy, @years, @tmpdate) SELECT @months = DATEDIFF(mm, @tmpdate, @dateTo) - CASE WHEN DAY(@dateFrom) > DAY(@dateTo) THEN 1 ELSE 0 END SELECT @tmpdate = DATEADD(mm, @months, @tmpdate) SELECT @days = DATEDIFF(dd, @tmpdate, @dateTo) SELECT @tmpdate = DATEADD(dd, @days, @tmpdate) SELECT @hours = DATEDIFF(hh, @tmpdate, @dateTo) SELECT @tmpdate = DATEADD(hh, @hours, @tmpdate) SELECT @minutes = DATEDIFF(mi, @tmpdate, @dateTo) SELECT @tmpdate = DATEADD(mi, @minutes, @tmpdate) SELECT @seconds = DATEDIFF(ss, @tmpdate, @dateTo) SELECT @tmpdate = DATEADD(ss, @seconds, @tmpdate) SELECT @milliseconds = DATEDIFF(ms, @tmpdate, @dateTo) IF (@years != '0') SELECT @ret = cast(@years AS VARCHAR(10)) + ' years ' + (CASE WHEN cast(abs(@months) AS VARCHAR(10)) != '0' THEN cast(abs(@months) AS VARCHAR(10)) + ' months ' ELSE '' END ) + (CASE WHEN cast(abs(@days) AS VARCHAR(10)) != '0' THEN cast(abs(@days) AS VARCHAR(10)) + ' days ' ELSE '' END) ELSE IF (@months != '0') SELECT @ret = cast(@months AS VARCHAR(10)) + ' months ' + (CASE WHEN cast(abs(@days) AS VARCHAR(10)) != '0' THEN cast(abs(@days) AS VARCHAR(10)) + ' days' ELSE '' END ) ELSE IF (@days != '0') SELECT @ret = cast(@days AS VARCHAR(10)) + ' days ' + (CASE WHEN cast(abs(@hours) AS VARCHAR(10)) != '0' THEN cast(abs(@hours) AS VARCHAR(10)) + ' hours' ELSE '' END ) ELSE IF (@hours != '0') SELECT @ret = cast(@hours AS VARCHAR(10)) + ' hours ' + (CASE WHEN cast(abs(@minutes) AS VARCHAR(10)) != '0' THEN cast(abs(@minutes) AS VARCHAR(10)) + ' minutes' ELSE '' END ) ELSE IF (@minutes != '0') SELECT @ret = cast(@minutes AS VARCHAR(10)) + ' minutes ' + (CASE WHEN cast(abs(@seconds) AS VARCHAR(10)) != '0' THEN cast(abs(@seconds) AS VARCHAR(10)) + ' seconds' ELSE '' END ) RETURN @ret END
Input:
select dbo.fn_relativeTime('2015-03-15') select dbo.fn_relativeTime('2015-03-15 11:30:25') select dbo.fn_relativeTime('2015-03-15 11:00') select dbo.fn_relativeTime('2015-01-15') select dbo.fn_relativeTime('2014-03-15') select dbo.fn_relativeTime('2014-01-15')
Output:
No comments:
Post a Comment