我有一段代码可以比较和验证日期。
问题:
此代码在执行期间花费了太多时间。当我评论此代码时,执行所需的时间要少得多。从这里我可以理解这段代码有一些开销。请提出建议以提高此代码的效率。
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;
}
}