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

后端 未结 4 497
爱一瞬间的悲伤
爱一瞬间的悲伤 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:34

    You can use the DateTime.ParseExact overload that takes a list of formats:

    private static string[] formats = new string[]
        {
            "MM/dd/yyyy HH:mm:ss tt",
            "MM/dd/yyyy HH:mm:ss",
            "M/dd/yyyy H:mm:ss tt",
            "M/dd/yyyy H:mm:ss"        
        };
    
    private static DateTime ParseDate(string input)
    {
        return DateTime.ParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
    }
    

    This will throw a FormatException if the passed string does not match any of the given formats. Notice that the formats expecting AM/PM should appear before identical formats without AM/PM ("MM/dd/yyyy HH:mm:ss tt" comes before "MM/dd/yyyy HH:mm:ss").

    Update
    As Henk points out in the comments, the same functionality is available when using TryParseExact which removes exception situation. Also, paired with nullable types this can be made a bit cleaner:

    private static DateTime? ParseDate(string input)
    {
        DateTime result;
        if (DateTime.TryParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
        {
            return result;
        }
        return null;
    }
    

    Now it will simply return a null reference if it fails to parse the input.

提交回复
热议问题