Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello everyone,

I just used DateDiff in sql, i.e Datediff(Day,fromdate,todate) and i got a nice result.

I used ..

SQL
Declare @fromdt date
Declare @todt date
set @fromdt=CONVERT(datetime,2012-05-30 ,105)
set @todt =CONVERT(datetime,2012-05-29  ,105)
SELECT datediff(DAY,@fromdt ,@todt )as 'DaysDifference'


it gave me output as : 1

but when i used..

SQL
Declare @fromdt date
Declare @todt date
set @fromdt=CONVERT(datetime,2012-05-30 ,105)
set @todt =CONVERT(datetime,2012-05-31  ,105)
SELECT datediff(DAY,@fromdt ,@todt )as 'DaysDifference'



it gave me output as : -1

now what i need is irrespective of whether the date is greater then from date or lesser then from date i want output as 1 only ...please suggest what should i do??

Thanks & Regards,
Krunal Panchal
Posted

You could use the ABS [^]function to convert...e.g

SQL
SELECT ABS(datediff(DAY,@fromdt ,@todt )) AS 'DaysDifference'
 
Share this answer
 
v2
Comments
Maciej Los 30-May-12 5:22am    
Good answer, my 5!
[no name] 31-May-12 2:38am    
Hi losmac,

I used your solution and it worked but again i am facing one problem i.e.

when i used

Declare @fromdt date
Declare @todt date
set @fromdt=CONVERT(datetime,2012-05-30 ,105)
set @todt =CONVERT(datetime,2012-06-01 ,105)
SELECT datediff(DAY,@fromdt ,@todt )as 'DaysDifference'
it gave me output as : 28 days instead it should give 2 days....

please help...

Regards,
Krunal Panchal
Dylan Morley 31-May-12 4:08am    
It's the way you're converting, try this...

Declare @fromdt date
Declare @todt date

set @fromdt=CONVERT(datetime,2012-05-30 ,105)
set @todt =CONVERT(datetime,2012-06-01 ,105)

PRINT @fromdt
PRINT @todt

Notice the date values? They are incorrect! Try changing the values used in the CONVERT function, see if you can fix it
use this query i think it will solve your problem

SQL
Declare @fromdt datetime
Declare @todt datetime
set @fromdt=CONVERT(datetime,2012-05-30 ,105)
set @todt =CONVERT(datetime,2012-05-31  ,105)
SELECT
(case when datediff(DAY,@fromdt ,@todt ) >0 then datediff(DAY,@fromdt ,@todt ) else abs(datediff(DAY,@fromdt ,@todt )) end)as 'DaysDifference'


if you don't want to check datediffernce is >0 or <=0 then you can use direct abs() method as per describe in solution 1.
 
Share this answer
 
Comments
Prasad_Kulkarni 14-Jun-12 3:37am    
Nothing wrong to down-vote for this answer. 5'ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900