Remove hours:seconds:milliseconds in DateTime object

前端 未结 9 2131
忘了有多久
忘了有多久 2021-01-17 09:43

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

Conventionally the DateTime object comes as

9条回答
  •  无人共我
    2021-01-17 10:18

    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.

提交回复
热议问题