Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Date Difference in Days Result Wrong

I want to calculate day difference between two dates.

When i calcualte Differane between '2017-01-01' and '2018-01-15' its 379 Days.

SELECT DATEDIFF(DD,'2017-01-01','2018-01-15') 

But when i split dates into two sections with addition .then i Got result 378.

select DATEDIFF( DD,'2017-01-01', '2017-12-31') + DATEDIFF( DD,'2018-01-01', '2018-01-15') 

anyone explain me why this happen ?

like image 670
Mr. Bhosale Avatar asked Mar 01 '26 02:03

Mr. Bhosale


2 Answers

This is very simple Math:

I:  <a,b>
II: <a,c>,<c+1,b>   where c is between a and b

I      II
b-a != b-(c+1) + c-a
b-a != b-c-1 + c-a
b-a != b-a-1       -- here is 1 missing day

To make it right you could use:

select DATEDIFF( DD,'2017-01-01', '2018-01-01') 
     + DATEDIFF( DD,'2018-01-01', '2018-01-15') 
like image 200
Lukasz Szozda Avatar answered Mar 02 '26 15:03

Lukasz Szozda


Datediff counts the boundaries of the datetype between the two dates.

The boundary "end of '2017-12-31'-start of '2018-01-01'" is included in the first case, but not the second.

like image 34
George Menoutis Avatar answered Mar 02 '26 14:03

George Menoutis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!