# calculate difference in milli seconds

calculating date difference using datediff in milliseconds is limited (For milliseconds, the maximum number is 24 days, 20 hours, 31 minutes and 23.647 seconds.).
the constraint is its return type INT.

Is there any other way to find out the diff in millisencods(no manual calculation plz..)

-Chandra
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
declare @d1 datetime, @d2 datetime
set @d1 = getdate()
set @d2 = dateadd(hour, 5, getdate()+25) -- 25 days and 5 hours later

select cast(datediff(day, @d1, @d2) as bigint) * 86400000 +
datediff(millisecond, dateadd(day, datediff(day, @d1, @d2), @d1), @d2) as datediff_ms
0
Commented:
You can make it a user-defined function as follows

create function ufn_datediff_ms(@d1 datetime, @d2 datetime)
returns bigint as
begin
return cast(datediff(day, @d1, @d2) as bigint) * 86400000 +
datediff(millisecond, dateadd(day, datediff(day, @d1, @d2), @d1), @d2)
end
go

-- how to use it (don't omit the dbo/owner prefix)
select dbo.ufn_datediff_ms('2004.01.01', '2004.01.26') as diff_in_ms

0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
The idea is to
- use bigint as return datatype
- calculate the difference in days and multiply by nb of millisecs in a day (1)
- calculate the diff in ms on the hours alone for the same day (reduce day offset) (2)
0
Author Commented:
this is as good as

return datediff(ss, @d1,@d2)*1000

0
Commented:
Bear in mind that the Datetime field in SQL only holds time to "accuracy of one three-hundredth of a second (equivalent to 3.33 milliseconds or 0.00333 seconds). " (from BOL)

/Richard

0
Commented:
>>this is as good as
return datediff(ss, @d1,@d2)*1000
<<
Not exactly the same though
Yours rounds the results at the second
0
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.