-3

This is date time format i want "2013-06-25 18:46:54.687" to pass in to sql server. How to convert in C#?

 DateTime LastUpdateTime=Convert.toDateTime(LastUpdateTime);
  //2013-06-25 18:46:54.687 with 3 index of millisecond
 sc.Parameters.Add("@LastUpdateTime", SqlDbType.DateTime).Value = LastUpdateTime;
Cœur
  • 37,241
  • 25
  • 195
  • 267
user983738
  • 993
  • 3
  • 13
  • 27

2 Answers2

2

You're using the wrong Data Typ in SQL.

The datetime2 can be considered as an extension of the existing datetime type that has a larger default fractional precision, and optional user-specified precision.


C# Format Milliseconds exactly the way you want. In an Example:

DateTime date2 = new DateTime(2008, 1, 1, 0, 30, 45, 125);
Console.WriteLine("Date: {0:o}", 
                  date2);           
// Displays the following output to the console:
//      Date: 2008-01-01T00:30:45.1250000

Look at Why is SQL Server losing a millisecond? and DateTime2 vs DateTime in SQL Server

These are great Question with good Answers, BTW.

Community
  • 1
  • 1
0

If your database query parameter is string, use following format:

LastUpdateTime.ToString("yyyy-MM-dd HH:mm:ss.fff")

Otherwise, it would be better to send datetime as original object, and let sql server do all conversions.

Alexander
  • 4,153
  • 1
  • 24
  • 37