Remove hours:seconds:milliseconds in DateTime object

locoboy picture locoboy · Dec 11, 2010 · Viewed 59.6k times · Source

I'm trying to create a string from the DateTime object which yields the format mm:dd:yyyy.

Conventionally the DateTime object comes as mm:dd:yyyy hrs:min:sec AM/PM.

Is there a way to quickly remove the hrs:min:sec AM/PM portion of the DateTime so that when I convert it ToString() it will only result in mm:dd:yyyy?

Answer

Mark Byers picture Mark Byers · Dec 11, 2010

To answer your question, no - you would have to store it in a different type. The most simple choice is to use a string.

string date = dateTime.ToString("MM:dd:yyyy");

However I'd also strongly advise against storing dates internally in your program as strings. This will make it difficult to do any calculations or comparisons on them. Furthermore I'd advise you against forcing a specific culture for your date representation as it means your application probably won't work as expected in other cultures than yours.

A slightly more sophisticated approach is to create a custom class which overrides ToString. I'd also avoid this though, because it will still be difficult to use your type with the standard library functions. You will have to convert back and forth all the time.

Just leave it as a DateTime and do the conversion to string only in the presentation layer. You can use DateTime.ToShortDateStringto print a user friendly culture aware string.