Search

Friday, August 3, 2012

Output time in days, hours and minutes

Use below query that will format a time span by days, hours and minutes.


DECLARE @FromTime DateTime
SET @FromTime = '2009-07-11 14:19:40.000'


DECLARE @ToTime DateTime
SET @ToTime = getUtcDate()


SELECT 
    CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)/(24*60)) + 'd ' 
  + CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)%(24*60)/60) + 'h '
  + CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)%60) + 'm' AS Format1
  , CASE 
      WHEN (((DateDiff(mi, @FromTime, @ToTime)/(24*60))) > 0) THEN
          CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)/(24*60)) + 'd ' 
        + CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)%(24*60)/60) + 'h '
        + CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)%60) + 'm'
      WHEN (((DateDiff(mi, @FromTime, @ToTime)%(24*60)/60)) > 0) THEN
          CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)%(24*60)/60) + 'h '
        + CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)%60) + 'm'
      ELSE
          CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)%60) + 'm'
    END AS Format2
  , CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)/(24*60)) + ':' 
  + RIGHT('00' + CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)%(24*60)/60), 2) + ':'
  + RIGHT('00' + CONVERT(VarChar(40), DateDiff(mi, @FromTime, @ToTime)%60), 2) AS Format3

No comments:

Post a Comment