We have used both a String and DateTime to create a Person class. Please note how the age is calculated.
Code for the Person Class:.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Employees
{
class Person
{
private String Name;
private DateTime Birthday;
public Person()
{
Name = "unknown";
Birthday = System.DateTime.Now;
}
public Person(String name, DateTime birthday)
{
Name = name;
Birthday = birthday;
}
public Person(String name, int year, int month, int day)
{
Name = name;
Birthday = new DateTime(year,month,day);
}
public void SetName(String s)
{
if (s != "") Name = s;
}
public void SetBirthday(DateTime bday)
{
Birthday = bday;
}
public void SetBirthday(int year, int month, int day)
{
Birthday = new DateTime(year,month,day);
}
public String getName()
{
return Name;
}
public DateTime getBirthday()
{
return Birthday;
}
public int Age()
{
// Get todays date.
DateTime today= System.DateTime.Now;
// Get birthday this year.
DateTime birthdayThisYear = new DateTime(today.Year, Birthday.Month, Birthday.Day);
// Calculate how old they will be this year;
int age= today.Year - Birthday.Year;
// If there birthday is after today, they aren't that age yet:
if (birthdayThisYear.Date > today.Date) age--;
return age;
}
}
}
Code in form load to create an instance of the Person class:
private void Form1_Load(object sender, EventArgs e)
{
// Create a new person
// Try a date that is prior to today and one that is after today.
Person person = new Person("Mark", 1998, 5, 21);
// Display the name and age:
Text = person.getName() + " is " + person.Age() + " years old.";
}