Which one:
is the recommended way to store date and time in SQL Server 2008+?
I\'m aware of differ
I concurr with @marc_s and @Adam_Poward -- DateTime2 is the preferred method moving forward. It has a wider range of dates, higher precision, and uses equal or less storage (depending on precision).
One thing the discussion missed, however...
@Marc_s states: Both types map to System.DateTime in .NET - no difference there
. This is correct, however, the inverse is not true...and it matters when doing date range searches (e.g. "find me all records modified on 5/5/2010").
.NET's version of Datetime
has similar range and precision to DateTime2
. When mapping a .net Datetime
down to the old SQL DateTime
an implicit rounding occurs. The old SQL DateTime
is accurate to 3 milliseconds. This means that 11:59:59.997
is as close as you can get to the end of the day. Anything higher is rounded up to the following day.
Try this :
declare @d1 datetime = '5/5/2010 23:59:59.999'
declare @d2 datetime2 = '5/5/2010 23:59:59.999'
declare @d3 datetime = '5/5/2010 23:59:59.997'
select @d1 as 'IAmMay6BecauseOfRounding', @d2 'May5', @d3 'StillMay5Because2msEarlier'
Avoiding this implicit rounding is a significant reason to move to DateTime2. Implicit rounding of dates clearly causes confusion: