17

Is there any difference between DateTime in c# and DateTime in SQL server?

odiseh
  • 25,407
  • 33
  • 108
  • 151

3 Answers3

24

Precision and range (so, everything important ;-p)

From MSDN:

.NET System.DateTime

The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.)

Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the GregorianCalendar calenda

Transact SQL datetime

Date Range: January 1, 1753, through December 31, 9999

Accuracy: Rounded to increments of .000, .003, or .007 seconds

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • excellent! I wanna to write a function in c# which gets a parameter of type string and convert it to datetime . I wanna to savethe return value of the function into DB. The function should take care of an empty string and in this case it should return null. But null can not be inserted. What 's wrong? – odiseh Jul 25 '09 at 09:13
  • 1
    Probably simply that you need to use DBNull.Value in .NET code to represent database null. – Marc Gravell Jul 25 '09 at 09:25
  • 2
    There's also the time zone aspect - even though DateTime doesn't have an associated time zone, it *can* know whether it's "local" or UTC. – Jon Skeet Jul 25 '09 at 16:59
12

You can also use datetime2 of SQL Server 2008. The precision there is 100ns as well. In fact, it was introduced to match the .NET DateTime precision.

datetime2 (Transact-SQL)

User
  • 30,403
  • 22
  • 79
  • 107
6

Yes.

The C# equivalent of the SQL datetime type is SqlDateTime

So, define the SQL call (stored procs with parameter collection of course) to use SQLDateTime. On advantage is you can trap any overflow or out of range error building the command rather than at execution time from the database engine.

gbn
  • 422,506
  • 82
  • 585
  • 676