I have two dates as per below and have my local culture is "en-IN"
string enInDateValue = "13-12-2021 12:00:00"; // dd/mm/yyyy
string enUSDateValue = "12-13-2021 12:00:00"; // mm/dd/yyyy
If I run the below code with Invariant Culture it date gets parsed with enUSDate.
DateTime.TryParse(enInDateValue, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out result)
DateTime.TryParse(enUSDateValue, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out result)
To solve the problem below is the code I am using and it is parsing the dates per culture.
public static bool DateTimeTryParse(string date, out DateTime result)
{
return (
DateTime.TryParse(date, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out result) ||
DateTime.TryParse(date, CultureInfo.CurrentCulture, DateTimeStyles.NoCurrentDateDefault, out result) ||
DateTime.TryParse(date, CultureInfo.CurrentUICulture, DateTimeStyles.NoCurrentDateDefault, out result)
);
}
If it fails with only Invariant Culture it goes to Current and same for UI Culture
So wanted to ask if that is the right to do? Or is there any other way around?
You need to specify the expected format explicitly. This small sample may be helpful: