Having trouble parsing this string into a date

63 Views Asked by At

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.

2

There are 2 best solutions below

3
Pawan Lakhara On BEST ANSWER

"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;
0
Lasse V. Karlsen On

When your input string and pattern is missing some of the date components, the current year, month, and day, is assumed, depending on which components you are missing.

It will not go looking for the last time that particular date and day combination was valid.

So that parsing is looking for a Wednesday 17th of November in 2022, and that date is a Thursday, not a Wednesday. 16th, however, is a Wednesday, so if we just change the code slightly:

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

Console.WriteLine($"{test}: {dateresult}");

Then it outputs:

True: 16.11.2022 00:00:00