The program needs to find the youngest (or oldest) person within a list. The birthday is actually a string. I converted the dates using Convert.ToDateTime(), which is working fine. However, in a few cases, the input is just a year, without the day and the month, e.g. "1945". The converter fails.
My questions:
1) what checker can I add in order to prevent such a run-time failure?
2) How can I convert it to date, without overriding strings that include the day and the month?
the code is:
DateTime curr_bday = Convert.ToDateTime(p.Birthday);
here is the full routine:
public string the_youngest(Persons _p2)
{
DateTime youngAge = Convert.ToDateTime("01/01/1005");
DateTime curr_bday;
string to_ret = "";
foreach (var p in _p2.persons)
{
curr_bday = Convert.ToDateTime(p.Birthday);
if (curr_bday < youngAge)
{
youngAge = curr_bday;
to_ret = p.Name + " : " + p.Birthday;
}
}
return (to_ret);
}
int.TryParse. If it is, initialize your birthday variable with a newly constructed DateTime where you specify only the year. Otherwise, parse the string as a date time