Simon Price Simon Price - 1 year ago 122
ASP.NET (C#) Question

String was not recognized as a valid DateTime when using SQL Date

I am using a date out of a SQL Server database that has the miliseconds on it like the example here "2016-10-07 21:00:29:987" which is held in a hidden field.

This is how the data is recorded, and this is one of the clauses of an update in a database.

When I try and pass this into the database as a parameter I get the "String was not recognized as a valid DateTime" error when using

var d = DateTime.ParseExact(hfDateLocked.Value.ToString(), "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);

If I remove the milliseconds off this works fine, but as its in the database with the milliseconds and this is one of the three clauses \ conditions I need to pass it through with this.

Any help would be gratefully received.

Edit 1

SqlParameter lockTimParam = new SqlParameter("@LockTime", SqlDbType.DateTime);

if (string.IsNullOrEmpty(hfLockTime.Value.ToString()))
lockTimParam.Value = DBNull.Value;
lockTimParam.Value = DateTime.ParseExact(hfLockTime.Value.ToString(), "yyyy-MM-dd hh:mm:ss:fff", CultureInfo.InvariantCulture);

Answer Source

Its a type-o in your format string, it does not match the format of the DateTime string that is being passed in (just the symbol between seconds and milliseconds).

.fff should be :fff.

var result = System.DateTime.ParseExact("2016-10-07 21:00:29:987", "yyyy-MM-dd HH:mm:ss:fff", System.Globalization.CultureInfo.InvariantCulture);

Or if the DateTime string is changed to use . instead of : then this works.

var result = System.DateTime.ParseExact("2016-10-07 21:00:29.987", "yyyy-MM-dd HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture);

Either way. The milliseconds in the returned DateTime string are segregated by a period (.) then use .fff in the format string, if its a colon (:) then use :fff in the format string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download