C
C#2y ago
DayKnight

Calculate obj Age [Answered]

Program
DateTime dtBirthDate = new DateTime(1971, 2, 23);
DateTime dtBirthDate = new DateTime(1971, 2, 23);
Student
public DateTime DateOfTime { get; set; }

public int GetAge()
{
var today = DateTime.Now;

var age = today.Year - DateOfTime;

if (DateOfTime.Date > today.AddYears(-age)) age--;

return age;
}
public DateTime DateOfTime { get; set; }

public int GetAge()
{
var today = DateTime.Now;

var age = today.Year - DateOfTime;

if (DateOfTime.Date > today.AddYears(-age)) age--;

return age;
}
I am trying to calculate the age, from the birthdate to now. but I am not sure how to do it when using properties
5 Replies
ero
ero2y ago
should DateOfTime not be DateOfBirth? except it's not. a datetime minus a datetime results in a timespan how stupid 'TimeSpan' does not contain a definition for 'TotalYears'
DayKnight
DayKnight2y ago
Ah okay thanks, if I get it as days I can just devide it by 365 and by doing that get the years
public int Age
{
get {

var today = DateTime.Today;
var age = DateOfTime - today;
age = Convert.ToInt32(ToString());
return _Age; }

set { _Age = value; }
}
public int Age
{
get {

var today = DateTime.Today;
var age = DateOfTime - today;
age = Convert.ToInt32(ToString());
return _Age; }

set { _Age = value; }
}
This is correct right? I am trying to converting it to a string? Whops catlaugh It's fixed now, thanks for the help
public int Age
{
get {

var today = DateTime.Today;
double antalDage = (DateOfTime - today).TotalDays;
int age = (int)antalDage / 365;
return _Age; }

set { _Age = value; }
}
public int Age
{
get {

var today = DateTime.Today;
double antalDage = (DateOfTime - today).TotalDays;
int age = (int)antalDage / 365;
return _Age; }

set { _Age = value; }
}
Thanks again catlaugh
public int Age
{
get {

double antalDage = (DateOfTime - DateTime.Now).TotalDays;
int _Age = (int)antalDage / 365;
return _Age; }

set { _Age = value; }
}
public int Age
{
get {

double antalDage = (DateOfTime - DateTime.Now).TotalDays;
int _Age = (int)antalDage / 365;
return _Age; }

set { _Age = value; }
}
But I get -51 for some reason That is werid
ero
ero2y ago
I feel like there shouldn't be a set You can't set the age of a person You can't set their date of birth either
DayKnight
DayKnight2y ago
It's fixed now, now it says +51 instead Remove set? Hmm, it does seem kinda useless here, that is true
Accord
Accord2y ago
✅ This post has been marked as answered!