Search code examples
c#asp.netasp.net-mvcvb.net

Why DateTime.TryParseExact is not working?


I am reading date from Excel and stored it in a variable In_Date, formats with which the date is to be compared is stored in Valid_Date_Formats

In_Date = "08/01/2020 00:00:00"

Valid_Date_Formats is an array which stores multiple date formats.

enter image description here

I am checking the format in if condition but it always fails.

If(DateTime.TryParseExact(In_Date, Valid_Date_Formats,
    System.Globalization.CultureInfo.InvariantCulture,
    System.Globalization.DateTimeStyles.None,
    DateTime_PlaceHolder))

What am I doing wrong here.


Solution

  • The input string has the following format: dd/MM/yyyy HH:mm:ss, which is missing from Valid_Date_Formats. (I'm assuming the 08 here is the day, because all your other formats start with the date part.)

    The following returns the correct date:

    DateTime.ParseExact("08/01/2020 00:00:00", new[] { "dd/MM/yyyy HH:mm:ss" }, CultureInfo.InvariantCulture, DateTimeStyles.None)
    

    In response to your comment: I'm not aware of a built-in method that would tell you which exact format string was used. If you really need to find out, I guess you could traverse the formats until you find a match:

    string[] formats = new[] { "dd/MM/yyyy", "dd/MM/yyyy HH:mm:ss" };
    string input = "08/01/2020 00:00:00";
    
    string usedFormat = null;
    DateTime date;
    
    foreach (string format in formats)
    {
        if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
        {
            usedFormat = format;
            break;
        }
    }