Nik
Nik

Reputation: 7273

C# SQL Server 2008 DATETIME2 Column

How can I work in C# with a DATETIME2 column through LINQ and get microsecond resolution? Right now, even with the server datatype set to DATETIME2, my LINQ object has a DateTime field, which doesn't seem to deal with microseconds.

Upvotes: 2

Views: 1036

Answers (1)

Benny Skogberg
Benny Skogberg

Reputation: 10681

Even though DATETIME2 handles microseconds, .NET 4 does not. If you need microseconds handled specifically, you can use procedures in SQL Server without reading values through your application.

The .NET reference says:

The fractional part of value is the fractional part of a millisecond. For example, 4.5 is equivalent to 4 milliseconds and 5000 ticks, where one millisecond = 10000 ticks.

string dateFormat = "MM/dd/yyyy hh:mm:ss.fffffff"; 
DateTime date1 = new DateTime(2010, 9, 8, 16, 0, 0);
Console.WriteLine("Original date: {0} ({1:N0} ticks)\n",
                  date1.ToString(dateFormat), date1.Ticks);

DateTime date2 = date1.AddMilliseconds(1);
Console.WriteLine("Second date:   {0} ({1:N0} ticks)",
                  date2.ToString(dateFormat), date2.Ticks);
Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)\n",
                  date2 - date1, date2.Ticks - date1.Ticks);                        

DateTime date3 = date1.AddMilliseconds(1.5);
Console.WriteLine("Third date:    {0} ({1:N0} ticks)",
                  date3.ToString(dateFormat), date3.Ticks);
Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)",
                  date3 - date1, date3.Ticks - date1.Ticks);                        
// The example displays the following output:
//    Original date: 09/08/2010 04:00:00.0000000 (634,195,584,000,000,000 ticks)
//    
//    Second date:   09/08/2010 04:00:00.0010000 (634,195,584,000,010,000 ticks)
//    Difference between dates: 00:00:00.0010000 (10,000 ticks)
//    
//    Third date:    09/08/2010 04:00:00.0020000 (634,195,584,000,020,000 ticks)
//    Difference between dates: 00:00:00.0020000 (20,000 ticks)  

Ref: DateTime.AddMilliseconds Method

Upvotes: 2

Related Questions