3

I want to show the posted date like 1 hr ago, or 30 min ago. This is my code:

declare @date datetime ='2014-07-24 11:50:22.033';
SELECT CASE WHEN DATEPART(DD,@date)=DATEPART(DD,GETDATE()) THEN 
  CASE WHEN DATEPART(HH,@date)=DATEPART(HH,GETDATE()) THEN
      CAST(DATEDIFF(MINUTE, @date, GETDATE()) AS NVARCHAR(50)) +' Minutes ago '
     ELSE 
      CAST(DATEDIFF(HOUR, @date, GETDATE()) AS NVARCHAR(50)) + ' Hours ago  ' END
 ELSE
  CAST(DATEDIFF(DAY, @date, GETDATE()) AS NVARCHAR(50)) + ' Days ago.. ' 
END AS Postedon 

I am getting a problem when the posted time is 11:50 and the server time is 12:10. In that case, I would like to show "20 min ago", but my code showing 1 hr ago.

0
5

As I said in the comments above, this should really be formatted in the application layer, where you are controlling the presentation to the user.

The issue lies with the way SQL handles the DATEDIFF function, in that comparing the HOUR difference between 08:59 and 09:00 will result in 1 hour, because the hour has ticked over and there is 1 hour difference between 8 and 9.

My solution may not be the most elegant, however it uses difference in MINUTE to get the number of hours passed since posting and the difference in HOUR to get the number of days.

 declare @date datetime ='2014-07-23 09:50:22.033';
    SELECT 
      CASE 
        WHEN DATEDIFF(SECOND, @date, GETDATE()) < 60 THEN ' Just Posted' 
        WHEN DATEDIFF(MINUTE, @date, GETDATE()) < 60 THEN CAST(DATEDIFF(MINUTE, @date, GETDATE()) AS VARCHAR(10)) + ' Minutes ago'
        WHEN DATEDIFF(MINUTE, @date, GETDATE()) < 24 * 60 THEN CAST(FLOOR(DATEDIFF(MINUTE, @date, GETDATE())/60) AS VARCHAR(10)) + ' Hours ago'
        ELSE CAST(FLOOR(DATEDIFF(HOUR, @date, GETDATE())/24) AS VARCHAR(10)) + ' Days ago'
    END AS Postedon 
0
0
select
        *,
        Days          = datediff(dd,0,DateDif),
        Hours         = datepart(hour,DateDif),
        Minutes       = datepart(minute,DateDif),
        Seconds       = datepart(second,DateDif),
        MS            = datepart(ms,DateDif)
from
        (
        select
                DateDif = EndDate-StartDate,
                aa.*
        from
                (  -- Test Data
                Select
                        StartDate = convert(datetime,'20140724 01:44:37.923'),
                        EndDate   = convert(datetime,'20140724 02:24:45.837')
                ) aa
        ) a

or:

DECLARE @submit_date DATETIME;
SET @submit_date = '2014-07-24 11:10:41.403';
SELECT 'Posted '
   + CONVERT(VARCHAR(40), 
      DATEDIFF(minute, @submit_date, GETDATE())/(24*60))
   + ' days, '
   + CONVERT(VARCHAR(40), 
      DATEDIFF(minute, @submit_date, GETDATE())%(24*60)/60)
   + ' hours, and '
   + CONVERT(VARCHAR(40), 
      DATEDIFF(minute, @submit_date, GETDATE())%60)
   + ' minutes ago.';
GO
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.