Calculate age with date of birth MVC5

1

I need to calculate a person's age from their birth date, but I am doing a poor calculation, I give you an example.

Pepito was born on December 17, 1997, at this moment Pepito is 19 years old, but to me in the calculation he shows me as if he were 20 years old.

My code is as follows:

//FECHA NACIMIENTO EN LA BASE DE DATOS
[Display(Name = "Fecha Nacimiento")]
        [DataType(DataType.Date)]
        public DateTime fecha_nacimiento { get; set; }
//CALCULO DE LA EDAD
 [NotMapped]
 [Display(Name = "Edad")]
 public int edad { get { return DateTime.Now.Year - fecha_nacimiento.Year; } }

In my database the date is as follows:

  

1997-12-17 00: 00: 00.000

    
asked by ByGroxD 03.04.2017 в 22:30
source

1 answer

2

Validation is required to know the current age, first the difference in years is obtained, then it is compared against the current date and if it is less it means that it is not fulfilled years, then, one year is subtracted to obtain the age today:

DateTime fechaNacimiento = new DateTime(1997, 12, 15);

DateTime now = DateTime.Today;
int edad = DateTime.Today.Year - fechaNacimiento.Year;

if (DateTime.Today < fechaNacimiento.AddYears(edad))
    --edad;

Here you can see the Demo

In your case, your code would look like this:

public int edad
{
    get
    {
        DateTime now = DateTime.Today;
        int edad = DateTime.Today.Year - fecha_nacimiento.Year;

        if (DateTime.Today < fecha_nacimiento.AddYears(edad))
            return --edad;
        else
            return edad;
    }
}
    
answered by 03.04.2017 / 22:58
source