Compare dates in T-SQL, ignoring the time part
Solution 1:
The most reasonable way to do this is to strip away the time portion of the datetime values and compare the results, and the best way to strip the time portion from a datetime is like this:
cast(current_timestamp as date)
I used to use and advocate a process that looked like one of the following two lines:
cast(floor(cast(getdate() as float)) as datetime)
dateadd(dd,0, datediff(dd,0, getDate()))
But now that Sql Server has the Date
type, which does not hold a time component, there is little reason to use either of those techniques.
One more thing to keep in mind is this will still bog down a query if you need to do it for two datetime values for every row in a where clause or join condition. If possible you want to factor this out somehow so it's pre-computed as much as possible, for example using a view or computed column.
Finally, note the DATEDIFF function compares the number of boundaries crossed. This means the datediff in days between '2009-09-14 11:59:59'
and '2009-09-15 00:00:01'
is 1, even though only 2 seconds has elapsed, but the DATEDIFF in days between '2009-09-15 00:00:01'
and '2009-09-15 11:59:59'
is still zero, even though 86,398 seconds elapsed. It doesn't really care at all about the time portion there, only the boundaries. Depending on what your query is trying to do, you might be able to use that to your advantage.
Solution 2:
WHERE DATEDIFF(day, date1, date2)=0
Solution 3:
In my own work, when I wanted to determine that two dates were equal irrespective of time of day, I've used the following:
WHERE CONVERT(VARCHAR, date1, 101) = CONVERT(VARCHAR, date2, 101)
Granted, "comparison" includes much more than equality and the above converts the dates to U.S.A format MM/DD/YYYY prior to making the comparison. So, performance implications and inability to compare date differences.
But...it does work.
Solution 4:
If one of your business requirements isn't well-served by your data model (e.g., you have a requirement to compare dates, but you aren't keeping track of dates, only of date-plus-times), look at the possibility of tuning the model, not the method of coping with it.
Would it be possible and helpful to store the date-only in an indexed computed column, or to store the date and time parts separately?
Solution 5:
Sorry for late answer.
i always use this syntax for date comparision
WHERE CONVERT(VARCHAR(8), date1, 112) = WHERE CONVERT(VARCHAR(8), date2, 112)
it always works great whenever we convert the date with 112 format code it return date in yyyyMMdd
format. it compare the date in string format without time but works great. thanks