-2

We had an assignment on school to calculate someones age using an Calendar. I think I am almost finished but I am stuck.

    int todaysYear;
    int selectedYear;
    todaysYear = DateTime.Now.Year;
    selectedYear = kalVerjaardag.SelectedDate.Year;
    txtLeeftijd.Text = todaysYear - selectedYear;

This is the current code I'm working with, at the very last part of my code it tells me that it cannot convert an "int" to "string". What do I do to fix this situation? Thanks in advance :D.

Nick Regeling
  • 17
  • 2
  • 5
  • 2
    Did you do any research for how to convert an `int` to a `string`? – chadnt Mar 10 '17 at 19:20
  • Your IDE is a very powerful tool, it's telling you exactly what the problem is. `txtLeeftijd.Text` is a `string` property and you are trying to assign an `int` to it. – maccettura Mar 10 '17 at 19:26
  • Note that code in the post *does not* calculate age in it's common meaning. That would be another duplicate. – Alexei Levenkov Mar 10 '17 at 20:30

2 Answers2

0

To have the person's age as string, you could do something alike:

int todaysYear;
int selectedYear;
todaysYear = DateTime.Now.Year;
selectedYear = kalVerjaardag.SelectedDate.Year;

txtLeeftijd.Text = Convert.ToString(todaysYear - selectedYear);
StfBln
  • 1,137
  • 6
  • 11
0

The problem of your code is conversion int to string, try this:

txtLeeftijd.Text = (todaysYear - selectedYear).ToString()

In your example it calculate only year, below code will give you year, month and days of age.

private string getAge()
{
    DateTime startTime = Convert.ToDateTime(selectedDateTime);
    DateTime endTime = DateTime.Today;
    TimeSpan span = endTime.Subtract(startTime);
    var totalDays = span.TotalDays;
    var totalYears = Math.Truncate(totalDays / 365);
    var totalMonths = Math.Truncate((totalDays % 365) / 30);
    var remainingDays = Math.Truncate((totalDays % 365) % 30);
    return string.Format("{0} year(s), {1} month(s) and {2} day(s)", totalYears, totalMonths, remainingDays);
}
csharpbd
  • 3,786
  • 4
  • 23
  • 32