Converting a Datetime from the datatable to a specific format of string C# ASP.NET

12,531

This is probably what you should do:

DateTime pmdate = (DateTime) dt.Rows[0]["PMDate"];
lblDate.Text = pmdate.ToString("g");

Note, this will render the string using the general date/time pattern for the current culture.

Share:
12,531
Mano
Author by

Mano

Updated on June 04, 2022

Comments

  • Mano
    Mano almost 2 years

    I am wokring on C#, ASP.Net So I take a datetime from the database and turn it into a datatable column. As for me, the database's datetime is very long and includes seconds and all sort of stuff and I want to change it into a specific format of:

    dd/MM/yy hh:mm

    so Iv'e tried this:

    lblDate.Text=(DateTime.ParseExact(dt.Rows[0]["PMDate"].ToString(),"dd/MM/yy hh:mm",System.Globalization.CultureInfo.InvariantCulture)).ToString();

    But sadly I get an error saying that the string was not identified as a valid DateTime. sadly, it is referring to the whole line above so I cannot tell what I did wrong.

    All I want to do is to take the DateTime from the DataBase, turn it into a DataTable column and from there into a string in the format mentioned above.

    Please help me, thanks in advance.

  • Mano
    Mano about 9 years
    Thank you, didn't know converting the datarow item to datetime was possible, that was the trick, thanks again. and also thanks about the "g" format, that has really saved me some time arranging the format.
  • Matt Johnson-Pint
    Matt Johnson-Pint about 9 years
    The field in the data row was already a DateTime. The API boxes it as an object. You just need to unbox it by casting. You should always do that, for any data type, rather than messing with strings. See Boxing and Unboxing in MSDN. For formats, see Standard Date and Time Format Strings in MSDN.