How does DateTime.TryParse know the date format?

Viewed 1703

Here is a scenario.

  • You have a string that represents a date i.e. "Jan 25 2016 10:10 AM".
  • You want to know whether it represents a date in a specific culture.
  • You want to know what dateTime pattern satisfies this date string.

Example:

  • Date string is "Jan 25 2016 10:10 AM"
  • Culture is en-US
  • The POSSIBLE format for it could be "MMM dd yyyy HH:mm tt"

Implementation:

  • To get the list of all dateTime patterns you can get a CultureInfo.DateTimeFormat.GetAllDateTimePatterns()
  • Then try the overloaded version of DateTime.TryParseExact(dateString, pattern, culture, DateTimeStyles.None, out resultingDate) for each of the patterns above and see whether it can parse a date.
  • That should give you the needed dateTime pattern.

HOWEVER if we iterate all those patterns it will not find any matches!

This is even more weird if you try and use a DateTime.TryParse(dateString, culture, DateTimeStyles.None, out resultingDate) and it DOES parse the correct date!

So the question is how come the DateTime.TryParse knows the pattern of a date string when this info is not a part of CultureInfo and how to get to this info in a culture?

Thanks!

2 Answers
Related