1

I am not able to convert the c# date time7/31/2017 3:13:49 PM to SQL date time while inserting the records to the database.

I am doing this using

DateTime dt = DateTime.Parse("11/23/2010");
string toSqlDate= dt.ToString("yyyy-MM-dd HH:mm:ss");
DateTime finalDate = DateTime.Parse(toSqlDate);

But it's giving me the error.

String was not recognized as a valid DateTime.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
Virender Thakur
  • 421
  • 7
  • 23

5 Answers5

1

After changing it to year/month/date this can help!

var sqlDate = finalDate.Date.ToString("yyyy-MM-dd HH:mm:ss");
Indrit Kello
  • 1,293
  • 8
  • 19
1

Your dateformat says 'year-month-day' while your date is 'month/day/year', that can't be right. Either change your dateformat or your date's formatting.

This should work:

DateTime dt = DateTime.Parse("2010-11-23 00:00:00");
string toSqlDate= dt.ToString("yyyy-MM-dd HH:mm:ss");
Carra
  • 17,808
  • 7
  • 62
  • 75
1

Change query to

insert into table_name (column1) values ('" + dt.Value.ToString("yyyy-MM-dd") + "')
1

Try the method DateTime.ParseExact and specify The date format that is suitable for you, here is an example from MSDN (https://msdn.microsoft.com/fr-fr/library/w2sa9yss(v=vs.110).aspx) :

var dateString = "06/15/2008";
var format = "d";
try {
     var result = DateTime.ParseExact(dateString, format, 
     CultureInfo.InvariantCulture);
     Console.WriteLine("{0} converts to {1}.", dateString, 
     result.ToString());
     }
  catch (FormatException) 
  {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }
1

The .Net DateTime maps directly to SQL Server DateTime. This means you don't need to worry about the display format at all, since DateTime does not have a display format.
All you need to do is pass the instance of the DateTime struct as a parameter to the SqlCommand:

SqlCommand.Parameters.Add("@DateTimeParam", SqlDbType.DateTime).Value = dt; 

Bonus reading: How do I create a parameterized SQL query? Why Should I?

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121