Question

I am working on a issue tracking application with asp.net and sql server 2005. While tracking the issues I am storing the deadline as datetime in the database and also if someone posts a message in the message board the posting date/time is also getting stored in the db as datetime.

Now my requirement is to show the issue deadline as "2 days left" when only 2 days are left, just like that when the deadline is already over it sud display 2 days behind schedule. This I think could be achieved with sql server datediff(), but in case of the messages I need to show like posted by 2 hours 3 minutes ago....or posted by 3 days 18 hours ago or something similar...(we can eliminate the hours if it was posted even 1 day before).

Tried Google but could not find anything useful. Would; appreciate your kind help as always.

Thanks in advance.

Was it helpful?

Solution

Use a variation on the following query, and adjust as needed. For other RDBMS's replace the date functions with appropriate equivalents.

SELECT  CASE
          WHEN DateValue-GETDATE() >= 1 THEN CAST(DATEPART(dy, DateValue-GETDATE()) AS varchar) + ' day(s) remaining'
          WHEN DateValue-GETDATE() >= 0 THEN CAST(DATEPART(hh, DateValue-GETDATE()) AS varchar) + ' hour(s) remaining'
          /*Note, it's convenient to switch around for negatives*/
          WHEN GETDATE()-DateValue <= '00:59' THEN CAST(DATEPART(mi, GETDATE()-DateValue) AS varchar) + ' minutes(s) overdue'
          WHEN GETDATE()-DateValue <= 1 THEN CAST(DATEPART(hh, GETDATE()-DateValue) AS varchar) + ' hours(s) overdue'
        ELSE
          CONVERT(varchar, DateValue-GETDATE(), 121)
        END AS Time_Scale

OTHER TIPS

Instead of doing this in SQL, you can use the .NET TimeSpan struct to get this functionality.

You can get it by subtracting one date from another, and it gives you the hours/minutes/seconds details you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top