C# : How to convert string to DateTime, where the string can have any of the standard datetime format

后端 未结 4 490
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-04 17:47

I had posted a question on DateTime to String conversion, I got many satisfying answers for that .. so I thank StackOverflow very much ..
Here is one more problem of String

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 18:35

    Take a look at the TryParseExact method. Here's an example with the first case:

    DateTime date;
    // I changed 02/31/2009 to 01/31/2009 because the first is not a valid date
    if (DateTime.TryParseExact("01/31/2009 01:59:59", "MM/dd/yyyy HH:mm:ss", null, DateTimeStyles.None, out date))
    {
        // string successfully parsed => do something with the date
    }
    

    You could then keep a list of different formats and try to parse the string with all of them until you succeed.

提交回复
热议问题