Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Day Date difference between two date calculation in SQL AND C# producing varying result

I am calculating the day difference in two dates. In C#

diffdays = (EndDate-StartDate).Days

so considering the Enddate as 6/26/2015 and startdate as 6/10/2015 the diffdays value is 15 as shown in the Autos section while debugging.

While in SQL server what I am doing is

SELECT DATEDIFF(day, StartDate, EndDate )

where EndDate is 6/26/2015 and startdate is 6/10/2015 and it gives a result 16.

I need these two day difference to be same. What is it that I am doing wrong?

like image 981
wingskush Avatar asked Jun 26 '15 11:06

wingskush


People also ask

How do I get the day difference between two dates in SQL?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference. Its value can be year , quarter , month , day , minute , etc.

How do I subtract a day from a date in SQL?

The DATE_SUB() function subtracts a time/date interval from a date and then returns the date.

How does datediff work in SQL?

The DATEDIFF() function returns an integer value that represents the difference between the start date and end date, with the date part as the unit. If the result is out of range for the integer (-2,147,483,647), the DATEDIFF() function returns an error.


2 Answers

The TimeSpan.Days property returns whole days only, dropping any fractional portion. Depending on the time portion of your two DateTime's, you could expect the behavior you're seeing.

Try taking the time portion out of the equation by using the Date property (and effectively setting both times to midnight):

diffdays = (EndDate.Date - StartDate.Date).Days

Alternatively, you can round up the TotalDays property (which includes fractional portions of days):

diffdays = Math.Ceiling((EndDate - StartDate).TotalDays);
like image 152
Grant Winney Avatar answered Oct 26 '22 16:10

Grant Winney


DATEDIFF function of SQL counts the number of times you pass the boundary specified as units, whereas .NET's DateTime.Subtract() function (you use this function when implicitly through the use of minus operator) returns the actual TimeSpan between the two dates, so you are bound to see differences between the two results.

EXAMPLE

The following query will return 1:

SELECT DATEDIFF(day, '1/1/2015 23:58:00', '1/2/2015 00:02:00')

There is a difference of only 4 minutes between the two dates, but since a day boundary has passed between the two dates (at 12:00 midnight), it returns 1. The same two dates will return a TimeSpan of 4 minutes in C#. If you check just the Days part (not TotalDays) of that TimeSpan object (as you're doing above), you'll get 0.

like image 30
dotNET Avatar answered Oct 26 '22 17:10

dotNET