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;
If you haven't even tried to resolve your issue, please don't expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.
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) A socialist is someone who will give you the shirt off *someone else's* back.
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