I have a string text that i want to parse/convert to DateTime,
the text can have a different formats (depending on the user who write it),
it can be "dd/MM/yyyy" or it can be "MM/dd/yyyy".
I am using DateTime.TryParseExact(string, formats[], provider, dateTimeStyles, out result)
as descripted here TryParseExact
Now the problem happens in the following cases
if (for example) string text = "06/01/2023"
The text could have two meanings
1st --> Day: 06, Month: 01, Year: 2023
2nd --> Day: 01, Month: 06, Year: 2023
My Question is when does the Method TryParseExact() return true
does it return true for the first format that matches text ?
or does it evalute all/each format inside the formats[] array ?
i have tried to search for a similar question, but i didn't seem to find one,
i have tried read this reference TryParseExactMultiple
i have tried this question
Thank you for your help in advance.
My code:
string text = "06/01/2023";
string[] formatsArray = new string[]
{
"yyyyMMdd",
"dd/MM/yyyy",
"dd-MMM-yy",
"MM/dd/yyyy",
"MM-dd-yyyy"
};
DateTime result;
DateTime.TryParseExact(text, formatsArray, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out result)
Output is:
result = Day: 06, Month: 01, Year: 2023
TryParseExactworks because there's no way for humans to say what the correct date is. This is why people should not use localized formats. Where does this string come from? A UI element? HTTP request? CSV file? Whatever creates the string should either be modified to useDateTimeinstead, or it should use the ISO8601 format.result = Day: 01, Month: 06, Year: 2023but still, how do I know which format is used in the parsing?TryParseExactit's better to useTryParsewith the correct locale.