Search code examples
c#datetimetryparse

Having trouble parsing this string into a date


In C#, I'm trying to parse a string using a custom pattern. The data will always be formatted as "ddd,M/d", so I'm trying to use TryParseExact:

string date = "Wed 11/17";
string pattern = "ddd M/d";
DateTime dateresult;
bool test = DateTime.TryParseExact(date, pattern, new CultureInfo("en-US"), 
                                   DateTimeStyles.None, out  dateresult);

Shouldn't test return true? I feel I'm missing something minor here.


Solution

  • "ddd M/d" This format is not acceptable in DateTime.TryParseExact(); for the reference please check https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-6.0

    string date = "01/20/2022";
    string pattern = "M/dd/yyyy";
    DateTime dateresult;
    bool test = DateTime.TryParseExact(date, pattern, new System.Globalization.CultureInfo("en-US"), System.Globalization.DateTimeStyles.NoCurrentDateDefault, out dateresult);
    
    // Return True;