The basic idea is just comparing 2 dates --- specific date and current date / GETDATE() ---, and returns in a simple wording. The longest time is YEAR, while the fastest time is will return "JUST NOW" if the different is within 1 hour.
- CREATE FUNCTION [dbo].[uf_WasInWord]
- (@dtDate DATETIME)
- RETURNS VARCHAR(255)
- AS
- BEGIN
- DECLARE @sReturns VARCHAR(255) = ''
- DECLARE @iHours INT = 0
- SET @iHours = DATEDIFF(HOUR, @dtDate, GETDATE())
- IF @iHours / 8766 > 0
- SET @sReturns = CONVERT(VARCHAR(10),@iHours / 8766) + ' year(s) ago'
- ELSE IF DATEDIFF(DAY, @dtDate, GETDATE()) >= 30
- SET @sReturns = CONVERT(VARCHAR(10),DATEDIFF(MONTH, @dtDate, GETDATE())) + ' month(s) ago'
- ELSE IF DATEDIFF(DAY, @dtDate, GETDATE()) > 6
- SET @sReturns = CONVERT(VARCHAR(10),DATEDIFF(DAY, @dtDate, GETDATE()) / 7) + ' week(s) ago'
- ELSE IF DATEDIFF(DAY, @dtDate, GETDATE()) > 2
- SET @sReturns = CONVERT(VARCHAR(10),DATEDIFF(DAY, @dtDate, GETDATE())) + ' day(s) ago'
- ELSE IF DATEDIFF(DAY, @dtDate, GETDATE()) >= 1
- SET @sReturns = 'Yesterday'
- ELSE IF DATEDIFF(HOUR, @dtDate, GETDATE()) > 1
- SET @sReturns = DATEDIFF(HOUR, @dtDate, GETDATE()) + ' hour(s) ago'
- ELSE
- SET @sReturns = 'Just now'
- RETURN @sReturns
- END
To use it, you can call the function directly from SQL Select like this example below:
- SELECT dbo.uf_WasInWord(created_date) FROM tips
No comments:
Post a Comment