Domanda

I am using this function to get the diff of two dates a person with the date joined of =03/03/1993 and a date left date of 06/02/2012 should be bringing back 8yrs 11mths but in mine its bringing back 9 years 2 months also i need it adapted If year in Date Joined is after the Year in Date Left you need to minus one Year. This is the same for months

    ALTER FUNCTION [dbo].[hmsGetLosText]
        (@FromDt as datetime,@DateLeftOrg as Datetime) 
    returns varchar(255)
    as
    BEGIN
        DECLARE @yy AS SMALLINT, @mm AS INT, @dd AS INT,
                @getmm as INT, @getdd as INT, @Fvalue varchar(255)

      SET @DateLeftOrg = CASE WHEN @DateLeftOrg IS NULL THEN GetDate()
           WHEN @DateLeftOrg = '1/1/1900' THEN GetDate()
           ELSE @DateLeftOrg  
           END

    SET @DateLeftOrg = CASE WHEN YEAR(@FromDt) > YEAR(@DateLeftOrg) THEN DateAdd(yy, -1, @DateLeftOrg)
    else @DateLeftOrg 
     end 


        SET @yy = DATEDIFF(yy, @FromDt, @DateLeftOrg)
        SET @mm = DATEDIFF(mm, @FromDt, @DateLeftOrg)
        SET @dd = DATEDIFF(dd, @FromDt, @DateLeftOrg)
        SET @getmm = ABS(DATEDIFF(mm, DATEADD(yy, @yy, @FromDt), @DateLeftOrg))
        SET @getdd = ABS(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, @yy, @FromDt), @DateLeftOrg), DATEADD(yy, @yy, @FromDt)), @DateLeftOrg))
        IF @getmm = 1
        set @getmm=0

        RETURN (
          Convert(varchar(10),@yy) + 'y ' + Convert(varchar(10),@getmm) + 'm ')
    END
È stato utile?

Soluzione 3

This is how I get your desired answer:

 DECLARE @D DATETIME
 SET @D  = CONVERT(datetime,'06/02/2002', 103)  - CONVERT(datetime,'03/03/1993', 103) 

 SELECT @D
 SELECT DATEPART(yyyy,@D) - 1900
 SELECT DATEPART(mm,@D) - 1
 SELECT DATEPART(day,@D) - 1

Altri suggerimenti

This is happening because the caller is somewhere converting the strings "03/03/1993" and "06/02/2012" to dates without being explicit about the date semantics and the months and days are getting swapped.

So "03/03/1993" is (coincidentally) unambiguous as "1993-MAR-03", but if "06/02/2012" is the same as "2012-FEB-06" then their difference is 8 years, 11 months. But if "06/02/2012" is interpreted as "2012-JUN-02", then their difference is 9 years, 2 months.

To fix this, the caller should either use a less ambiguous format, such as "2012-02-06" (which is always Feb 6th) or explicitly qualify and cast it. This is how you would do that in T-SQL:

SELECT @date = CONVERT(DATETIME, '06/02/2012', 103)

which is also always interpreted as Feb 6th.

Simply do this to get the delta:

DECLARE @Delta DATETIME

SET @Delta = @End - @Start

So if you were expecting 8 years then the @Delta year would 1908, then you get the month of @Delta, the day, hour, min. etc....

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top