October 22, 2020 at 7:34 am
hi all,
good day
I've write the below script to get the difference between two times
for this example the result should be 2:20 , I don't know why it gives 20:00
can anybody advise?
declare
@hFrom nvarchar(2)='9',
@mFrom nvarchar(2)='0',
@hTo nvarchar(2)='11',
@mTo nvarchar(2)='20'
SELECT CONVERT(CHAR(5), DATEADD(MINUTE, 60*(DATEDIFF(MINUTE,CAST(@hFrom +':'+@mFrom AS TIME), CAST(@hTo +':'+ @mTo AS TIME))), 0), 108) as TimeDiff
October 22, 2020 at 7:45 am
sorry, it seems that i need to sleep 🙂
i forget to divide by 60, it should be as below
SELECT CONVERT(CHAR(5), DATEADD(MINUTE, 60*(DATEDIFF(MINUTE,CAST(@hFrom +':'+@mFrom AS TIME), CAST(@hTo +':'+ @mTo AS TIME)))/60, 0), 108) as TimeDiff
October 22, 2020 at 11:55 am
Using more appropriate data types:
DECLARE @hFrom TINYINT = 9
, @mFrom TINYINT = 0
, @hTo TINYINT = 11
, @mTo TINYINT = 20;
WITH x
AS
(SELECT TotalMins = DATEDIFF(MINUTE, TIMEFROMPARTS(@hFrom, @mFrom, 0, 0, 0), TIMEFROMPARTS(@hTo, @mTo, 0, 0, 0)))
SELECT TimeDiff = TIMEFROMPARTS(calcs.hrs, calcs.mins, 0, 0, 0)
FROM x
CROSS APPLY
(SELECT hrs = x.TotalMins / 60, mins = x.TotalMins % 60) calcs;
The absence of evidence is not evidence of absence.
Martin Rees
You can lead a horse to water, but a pencil must be lead.
Stan Laurel
October 22, 2020 at 1:20 pm
The problem is that you multiplied the minutes difference by 60; just get rid of the "60*".
SELECT CONVERT(CHAR(5), DATEADD(MINUTE, (DATEDIFF(MINUTE,CAST(@hFrom +':'+@mFrom AS TIME), CAST(@hTo +':'+ @mTo AS TIME))), 0), 108) as TimeDiff
SQL DBA,SQL Server MVP(07, 08, 09) "It's a dog-eat-dog world, and I'm wearing Milk-Bone underwear." "Norm", on "Cheers". Also from "Cheers", from "Carla": "You need to know 3 things about Tortelli men: Tortelli men draw women like flies; Tortelli men treat women like flies; Tortelli men's brains are in their flies".
October 22, 2020 at 1:22 pm
Disclaimer: I'm not saying this is the correct way to do this. But it's compact and nice to look at imo. String integers convert implicitly and time differences are easily calculated. Something like this (as a novelty)
declare
@hFrom nvarchar(2)='9',
@mFrom nvarchar(2)='0',
@hTo nvarchar(2)='11',
@mTo nvarchar(2)='20'
select d.mins/60 d_hrs,
d.mins%60 d_mins
from (select ((@hTo*60+@mTo)-(@hFrom*60+@mFrom)) mins) d;
d_hrsd_mins
220
Aus dem Paradies, das Cantor uns geschaffen, soll uns niemand vertreiben können
October 22, 2020 at 9:07 pm
Just curious... where are the original "from" and "to" values coming from? I ask because, if we know that, we might be able to...
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply