如何通过 LINQ 在 C# 中使用 DATETIME2 列并获得微秒分辨率?现在,即使服务器数据类型设置为 DATETIME2,我的 LINQ 对象也有一个 DateTime 字段,它似乎不处理微秒。
最佳答案
即使 DATETIME2 处理微秒,.NET 4 也不会。如果需要专门处理微秒,则可以在 SQL Server 中使用过程,而无需通过应用程序读取值。
.NET 引用说:
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)
关于C# SQL Server 2008 DATETIME2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5637301/