right - updated the code:
If a region is using a format that allows single-digit days or months, then unfortunately the user MUST specify 2 digits for month and day, else it's impossible to discern the date: eg: 1122010 - is that 1 Dec, or 11 Feb 2010? It must be specified: 01122010 or 11012010
public static bool TryParseNumberAsDate(string date, out DateTime dateTime)
{
bool parsedSuccess = false;
dateTime = DateTime.Now;
int isNumber;
//1) Determine if no separators were specified
if (int.TryParse(date, NumberStyles.Integer, CultureInfo.CurrentCulture, out isNumber)) //ie: If the user typed only numerics, leaving out any separators
{
//2) Determine if the length without separators is correct
string longestDate = new DateTime(1977, 12, 20).ToShortDateString();
string longestDateFormatWithoutSeparator = new string(longestDate.Where(ch => char.IsDigit(ch)).ToArray());
if (date.Length == longestDateFormatWithoutSeparator.Length) //NOTE: Some cultures write "DD" "01" as "1" - force them to type "01"
{
//3) Determine what the separator is
char separator = longestDate.Where(ch => !char.IsDigit(ch)).First();
//4) Insert the separator into the date string
List<int> separatorIndexes = new List<int>();
int currentIndex = longestDate.IndexOf(separator, 0, longestDate.Length);
while (currentIndex > 0)
{
separatorIndexes.Add(currentIndex);
currentIndex = longestDate.IndexOf(separator, currentIndex + 1, longestDate.Length - currentIndex - 1);
}
foreach (int separatorIndex in separatorIndexes)
{
date = date.Insert(separatorIndex, new string(separator, 1));
}
//5) Parse the new date string to check validity
DateTime parseDate;
if (DateTime.TryParse(date, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out parseDate))
{
dateTime = parseDate;
parsedSuccess = true;
}
}
}
return parsedSuccess;
}