Hi guys
I have run into a datetime related problem, my program needs to varify whether a user entered date string is valid.
The program is designed to process date value ranges from 01/01/2000 ~ 31/12/2020 and the string format is like "12 Feb 10".
The problem I am facing is, sometimes user enters value like "30 Feb 10" (this value is invalid), which passes format check but DateTime.TryParse will interprate this string as "10/02/1930 12:00:00am".
My solution to this problem is to extract the date, month, year value from the string seperatly and try to recontruct the date string. see the following code.
private static void IsValidDateValue(string userInputValue, CustomValidatorExtended custValidator, string errorMessage, ref bool isValid)
{
Regex regexValue = new Regex(SHORT_DATE_VALUE);
if (regexValue.IsMatch(userInputValue))
{
Match match = regexValue.Match(userInputValue);
int dayValue;
if (!Int32.TryParse(match.Groups["date"].Value, out dayValue))
{
custValidator.ErrorMessage = errorMessage;
isValid = false;
return;
}
int monthValue;
if (!Int32.TryParse(ConvertMonthNameToNumber(match.Groups["month"].Value).ToString(), out monthValue))
{
custValidator.ErrorMessage = errorMessage;
isValid = false;
return;
}
//this application is designed to handle only from year 2000 ~ 2020 and user only suppose to enter 2 digits for year
int yearValue;
if (!Int32.TryParse("20" + match.Groups["year"].Value, out yearValue))
{
custValidator.ErrorMessage = errorMessage;
isValid = false;
return;
}
DateTime dtParse;
if (!DateTime.TryParse(yearValue + "-" + monthValue + "-" + dayValue, out dtParse))
{
custValidator.ErrorMessage = errorMessage;
isValid = false;
return;
}
}
else
{
isValid = true;
return;
}
}
Is there an easier way using .net framework default method to solve this date year value swap problem ?
Thank & Regards,