Calculating Duration Using DATETIME Start and End Dates (SQL Spackle)

  • Comments posted to this topic are about the item Calculating Duration Using DATETIME Start and End Dates (SQL Spackle)[/url]

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Thank you for the spackle Jeff but it looks like there is a small crack in it as it makes the assumption that the end time is always greater than the start time. This is the reason why I prefer to use double cast, first to varbinary and then to bigint.

    SELECT

    StartDT

    ,EndDT

    ,Duration = STUFF(CONVERT(VARCHAR(20),EndDT-StartDT,114),1,2,DATEDIFF(hh,0,EndDT-StartDT))

    ,DurationI = STUFF(CONVERT(VARCHAR(20),StartDT-EndDT,114),1,2,DATEDIFF(hh,0,StartDT-EndDT))

    ,cast(cast(StartDT as varbinary(128)) as bigint) As StartTicks

    ,cast(cast(EndDT as varbinary(128)) as bigint) AS EndTicks

    ,cast(cast(StartDT as varbinary(128)) as bigint)-cast(cast(EndDT as varbinary(128)) as bigint) as XmY

    ,cast(cast(EndDT as varbinary(128)) as bigint)-cast(cast(StartDT as varbinary(128)) as bigint) as YmX

    FROM #JBMTest;

  • There is one more thing to notice about the first query.

    You assign the value "2000-02-01 12:34:56.789" to @EndDT but the query returns "2000-01-02 12:34:56.789".

    Either make sure you are using "SET DATEFORMAT YMD" or use an unambiguous date format for the string literal "2000-02-01T12:34:56.789".

  • Here is my simple method to format the output to a more readable format:

    CAST(GETDATE() - @StartDT AS TIME(2)) AS Duration

  • Do you have a good query for formatting duration (or age) in Years, Months, Days?

    So often in my world, I am asked to find out who was the youngest or oldest to achieve something, or how long has it been since something has been achieved in a span of that range. I have a function that will do it, but I'd be interested to see how others have done it.

    Of course I know that not all months have 30 days, so saying that someone is 16 years, 8 months, and 7 days old could be equivalent to 16 years, 8 months, and 10 days if months with 31 and 28 days are involved in the calculation. You also cannot just assume that a month is 30 days in your calculation since you could end up with 16 years, 12 months, and 4 days which would immediately look ridiculous and completely destroy your credibility. Number of days is the truest measure for comparison, but telling someone that the youngest was 6095 days old has no meaning to most people.

    Anyone out there got a good method for YMD?

  • I'm guessing the @EndDT for the first code example should have been.

    @EndDT = '2000-01-02 12:34:56.789'

    That gives the same answer as the example.

  • Dennis Wagner-347763 (1/16/2014)


    Do you have a good query for formatting duration (or age) in Years, Months, Days?

    So often in my world, I am asked to find out who was the youngest or oldest to achieve something, or how long has it been since something has been achieved in a span of that range. I have a function that will do it, but I'd be interested to see how others have done it.

    Of course I know that not all months have 30 days, so saying that someone is 16 years, 8 months, and 7 days old could be equivalent to 16 years, 8 months, and 10 days if months with 31 and 28 days are involved in the calculation. You also cannot just assume that a month is 30 days in your calculation since you could end up with 16 years, 12 months, and 4 days which would immediately look ridiculous and completely destroy your credibility. Number of days is the truest measure for comparison, but telling someone that the youngest was 6095 days old has no meaning to most people.

    Anyone out there got a good method for YMD?

    Which years in the calendar should we use to calculate this? The actual span between the two dates? Then comparisons between calculations made from different pairs of dates are not strictly compatible. The biggest reason is the occurrence of leap years within ranges. It might may a difference of only a day, but it sounds like for your applications, that may be important.

    But, you could just do three DATEPART calculations and be done with it.

    [font="Verdana"]Please don't go. The drones need you. They look up to you.[/font]
    Connect to me on LinkedIn

  • Oliver Gugolz (1/16/2014)


    Here is my simple method to format the output to a more readable format:

    CAST(GETDATE() - @StartDT AS TIME(2)) AS Duration

    But that only displays the fractional hours portion of the difference. You still lose the days converted to hours that Jeff's method preserves.

    [font="Verdana"]Please don't go. The drones need you. They look up to you.[/font]
    Connect to me on LinkedIn

  • My specific use of the datetime field is to see if it occurs

    within a user specified date range.

    The examples I received with the stored procedures (from software application vendor)

    had the user enter full date and time (2014-01-14 23:59.59)when I am not interested in the time aspect.

    I changed to have the user just enter the date ('2014-01-14') which defaults to zero time.

    If inclusive start date and end date are entered, with the default zero time, I would miss

    the last date, so I compare

    between @startdate and @enddate + 1

    which does include the entire enddate.

  • Thanks for the feedback folks. I'm on my way to work and will look into your replies when I get home.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Eirikur Eiriksson (1/16/2014)


    Thank you for the spackle Jeff but it looks like there is a small crack in it as it makes the assumption that the end time is always greater than the start time. This is the reason why I prefer to use double cast, first to varbinary and then to bigint.

    SELECT

    StartDT

    ,EndDT

    ,Duration = STUFF(CONVERT(VARCHAR(20),EndDT-StartDT,114),1,2,DATEDIFF(hh,0,EndDT-StartDT))

    ,DurationI = STUFF(CONVERT(VARCHAR(20),StartDT-EndDT,114),1,2,DATEDIFF(hh,0,StartDT-EndDT))

    ,cast(cast(StartDT as varbinary(128)) as bigint) As StartTicks

    ,cast(cast(EndDT as varbinary(128)) as bigint) AS EndTicks

    ,cast(cast(StartDT as varbinary(128)) as bigint)-cast(cast(EndDT as varbinary(128)) as bigint) as XmY

    ,cast(cast(EndDT as varbinary(128)) as bigint)-cast(cast(StartDT as varbinary(128)) as bigint) as YmX

    FROM #JBMTest;

    I got:

    Msg 8115, Level 16, State 2, Line 15

    Arithmetic overflow error converting expression to data type datetime.

    when I ran it for date differences greater than about 148 years. Maybe not a problem for some implementations, but something to be aware of.

    [font="Verdana"]Please don't go. The drones need you. They look up to you.[/font]
    Connect to me on LinkedIn

  • Mikael Eriksson SE (1/16/2014)


    There is one more thing to notice about the first query.

    You assign the value "2000-02-01 12:34:56.789" to @EndDT but the query returns "2000-01-02 12:34:56.789".

    Either make sure you are using "SET DATEFORMAT YMD" or use an unambiguous date format for the string literal "2000-02-01T12:34:56.789".

    Thanks for the heads up, Mikael... it wasn't all that about unambiguous dates (which is whatI used)... it was a phat phinger during transfer of the code to the article submission site. I've submitted a correction that they'll, hopefully, be able to get to right away.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • cready27 (1/16/2014)


    I'm guessing the @EndDT for the first code example should have been.

    @EndDT = '2000-01-02 12:34:56.789'

    That gives the same answer as the example.

    Correct. I've submitted a correction. Apparently, I phat phingered the code during my final submittal to the article submittal software.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Calculations are done using a calendar year.

    For example if person A was born October 16, 1995, and we want to figure out how old he/she was on January 15, 2014, we can easily use DATEDIFF(day, '10/16/95', '1/15/14) to get 6,666 days, but we want the result to be formatted as 18 years, 2 months, 30 days. The years are easy, and the months aren't too bad, but the days calculation is based on December having 31 days, so there are 30 days between December 16, 2013 (18 years and 2 months after 10/16/95) and January 15, 2014. However, if we were calculating from 10/16/95 to March 15, 2014, our answer should be 18 years, 4 months, 27 days since there are only 28 days in February. And yes, you are correct that leap years do prevent an issue and need to be addressed.

    The issue with doing simple DATEDIFF in SQL is that it does a straight subtraction. From the example above:

    DATEDIFF(year, '10/16/95', '1/15/14') = 19 (but only 18 full years elapsed)

    DATEDIFF(month, '10/16/95', '1/15/14')%12 = 3 (but only 2 full months elapsed)

    Days is a real mess.

    How about this: DATEDIFF(YEAR, '12/31/13', '1/1/14') = 1! (not the factorial) when only 1 day has elapsed

    When comparing who is older when they achieved their Super Duper Fantastical Grandmaster Status, you have to use number of days because it is not affected by leap years, days in a month, etc.

    So if person A above was compared to person B who was born December 14, 1995 and achieved this noteworthy status on March 15, 2014, then both of them would be 6,666 days old:

    DATEDIFF(day, '10/16/95', '1/15/14') = DATEDIFF(day, '12/14/95', '3/15/14') = 6,666

    However, when formatted as YMD, person A is 18 years, 2 months, 30 days while person B is 18 years, 3 months, 1 day, which would make person A seem younger. My original response states why you can't just fix 30 days in a month or you could end up with x years, 12 months, and 4 days when 364 days elapsed from the previous year anniversary.

    I always use days when figuring out a "top 10" list, but I always format the answer as YMD so the age is meaningful to the audience.

  • I can't spend much more time on the discussions that are unfolding until I get home from work tonight but the folks at SQLServerCentral have posted the correction to the first code window that a couple of you brought up. Thank you for the help there.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 15 posts - 1 through 15 (of 57 total)

You must be logged in to reply to this topic. Login to reply