简体   繁体   中英

c# - Convert string to datetime with DateTime.ParseExact

I have to convert a string extract from a file to datetime. The problem is that my string doesn't have a unique format. For example my string can be something like : 19-05-2016 1:24:09:560 or 19-05-2016 21:24:09:56 or 19-05-2016 10:24:09:560 or 19-05-2016 10:24:09 and so on. I didn't encounter all the possibilities yet ( these strings are pulled out of an json response from an API call)

This is how my code looks like

public static DateTime ConveDateTime(string a)
{
    DateTime finished;
    try
    {
        finished = DateTime.ParseExact(a, "dd-MM-yyyy HH:mm:ss:fff", CultureInfo.InvariantCulture,
            DateTimeStyles.AssumeUniversal |
            DateTimeStyles.AdjustToUniversal);
    }
    catch (Exception)
    {
        try
        {
            finished = DateTime.ParseExact(a, "dd-MM-yyyy HH:mm:ss:ff", CultureInfo.InvariantCulture,
                DateTimeStyles.AssumeUniversal |
                DateTimeStyles.AdjustToUniversal);
        }
        catch (Exception)
        {
            try
            {
                finished = DateTime.ParseExact(a, "dd-MM-yyyy HH:mm:ss:f", CultureInfo.InvariantCulture,
                    DateTimeStyles.AssumeUniversal |
                    DateTimeStyles.AdjustToUniversal);
            }
            catch (Exception)
            {
                try
                {
                    finished = DateTime.ParseExact(a, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture,
                        DateTimeStyles.AssumeUniversal |
                        DateTimeStyles.AdjustToUniversal);
                }
                catch (Exception)
                {
                    try
                    {
                        finished = DateTime.ParseExact(a, "dd-MM-yyyy H:mm:ss:fff", CultureInfo.InvariantCulture,
                            DateTimeStyles.AssumeUniversal |
                            DateTimeStyles.AdjustToUniversal);
                    }
                    catch (Exception)
                    {
                        try
                        {
                            finished = DateTime.ParseExact(a, "dd-MM-yyyy H:mm:ss:ff", CultureInfo.InvariantCulture,
                            DateTimeStyles.AssumeUniversal |
                            DateTimeStyles.AdjustToUniversal);
                        }
                        catch (Exception)
                        {

                            finished = DateTime.ParseExact(a, "dd-MM-yyyy H:mm:ss:f", CultureInfo.InvariantCulture,
                            DateTimeStyles.AssumeUniversal |
                            DateTimeStyles.AdjustToUniversal);
                        }                            
                    }
                }
            }
        }
    }

    return finished;
}

I want to know if there is any better solution in converting a string than the solution I have.

DateTime.ParseExact has an overload that takes a string array of possible formats to use for parsing. Use that overload and reduce your code to a line or two.

string[] formats = new string[] {"dd-MM-yyyy HH:mm:ss:fff",
                                 "dd-MM-yyyy H:mm:ss:fff",
                                 "dd-MM-yyyy HH:mm:ss:f",
                                 "dd-MM-yyyy HH:mm:ss", 
                                 ....};

finished = DateTime.ParseExact(a, formats, CultureInfo.InvariantCulture,
                DateTimeStyles.AssumeUniversal |
                DateTimeStyles.AdjustToUniversal);

If you don't know all the possible formats you could also read them from an external file to avoid recompiling your application if a new format pops up

Also, as said in the comments below, I prefer to use DateTime.TryParseExact to have more control on the outcome of the parsing and avoid a costly exception handling in case of a format not recognized.

What about using DateTime.Parse() instead of DateTime.ParseExact()? DateTime.Parse() is far more forgiving than ParseExact. This way you don't have to define all the possible formats?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM