I have a piece of code which compares and validate dates.
Problem:
This code is taking too much time during execution. When i comment this code the execution takes much less time. From this i can understand this code has some overhead in it. Please make suggestions to improve efficiency of this code.
DateTime regDate;
DateTime dob;
extractDate(buffer[5], buffer[6], out regDate, out dob);
private void extractDate(string date, string rDate, out DateTime regDate, out DateTime dob)
{
if (date == "") // Date of birth is not given;
{
regDate = getStandardDate(rDate); // MM/DD/YYYY
dob = regDate.AddYears(-18);
}
else
{
dob = getStandardDate(date);
}
if (rDate == "")
{
dob = getStandardDate(date);
regDate = dob.AddYears(18);
}
else
{
regDate = getStandardDate(rDate);
}
}
private DateTime getStandardDate(string date)
{
bool checkDate = isValidDate(date);
if (checkDate)
{
IFormatProvider culture = new System.Globalization.CultureInfo("en-gb", true);
DateTime dt;
if (karachiDateFormat)
{
dt = DateTime.Parse(date);
}
else
{
dt = DateTime.Parse(date, culture);
}
return dt.Date;
}
else
{
return DateTime.Now.Date;
}
}
private bool isValidDate(string date)
{
IFormatProvider culture = new System.Globalization.CultureInfo("en-gb", true);
DateTime Ttime;
if (!karachiDateFormat)
{
Ttime = DateTime.Parse(date, culture);
}
else
{
Ttime = DateTime.Parse(date);
}
date = string.Empty;
date = Ttime.Date.ToShortDateString();
string[] splitDate = date.Split('/');
int day = Int32.Parse(splitDate[1]);
int month, year;
month = Int32.Parse(splitDate[0]);
year = Int32.Parse(splitDate[2]);
DateTime time = DateTime.Now;
if ((day > 0 && day < 32) && (month > 0 && month <= 12) && (year > 1950 && year < time.Year))
{
return true;
}
else
{
return false;
}
}
I believe you can speed up your code by changing the isValidDate method.
From what I understand you validate the text if it matches the date pattern. I would try to completely remove this method and replace
DateTime.Parsein your getStandardTime withDateTime.TryParseThis will take care of both validation and parsing. See here DateTime.TryParse MethodIf you need some validation of your date, than do this with DateTime structure, not with string repesentation.
Also you are parsing two dates (date and rDate). maybe using Parallel.Invoke could help, but I am not sure about this.