2

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.

1
  • 2
    Is it really a string in the database? (You're parsing it as that...) Any reason it's not a datetime? And if you're finding that you can't narrow a problem down due to a line doing too much, you should break that line down into several statements... Also, are you aware that with hh you get a 12 hour format, and you're not including an am/pm designator? Commented Mar 25, 2015 at 20:46

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.