Search code examples
c#asp.netdatetimeado.netstring-parsing

datetime format in ASP.NET C# not recognized


I have a column in my database with the following content:

status
2018-12-31 15:31:56.000 (result of a select in SMSS)

I am trying to get this column's data in ASP.NET code behind page through a query in C#:

var connectionString = System.Configuration.ConfigurationManager.AppSettings["connection"];
SqlConnection con = new SqlConnection(connectionString);

DataTable dt = new DataTable();            

SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 1 [status] from [tablename] where idNo = '" + idNo+ "'", con);

con.Open();
da.Fill(dt);

if (dt.Rows.Count > 0)
{
    Debug.WriteLine("\n Rows extracted."); // -> Error thrown here.

    Debug.WriteLine("\n Rows content:" + DateTime.ParseExact(dt.Rows[0][0].ToString(), "yyyy-MM-dd hh:mm:ss.000", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None));

    con.Close();
    da.Dispose();
}

No matter what I try I always get either

String was not recognized as a valid DateTime

or the datetime is not recognized as part of the Gregorian calendar.

I have tried to display the dt.Rows[0][0] content directly, but then I get an error about the date not being in the Gregorian calendar.

Are there any steps I could undertake to understand what is going on with this?

Working with DateTime is an absolute nightmare in C#, I wished MS would finally fix this.

Please don't point me to the docs or other articles, that's obviously where I come from...


Solution

  • Case is important when it comes to format strings. See: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

    The string you actually want is:

    yyyy-MM-dd HH:mm:ss.fff
    

    Note the case of Months, Hours and minutes.

    h = 12 hour clock, H = 24 hour clock.

    Demo

    Now you just need to adopt best practices for calling the database. Use parameterised queries and read up on using statements