HOW TO CALCULATE AGE IN C#?

john rob

Total Post:108

Points:756
Posted by  john rob
C# 
C#
 1128  View(s)
Ratings:
Rate this:
How to calculate age from DOB
 class Personal{
 public DateTime DateOfBirth { get; set; }
 public string Age { get; set; }
 }
        Personal per=new Personal();
       Console.WriteLine("Enter the Date Of Birth :",per.DateOfBirth);        
 per.DateOfBirth = DateTime.Parse(Console.ReadLine());

 public string GetAge(DateTime DateOfBirth)
         {
        }
How can i write for function to calculate age from DOB and display
       Console.WriteLine("The DOB is" +DateOfBirth);
       Console.WriteLine("the Age is ...." +Age);
DOB is 04/02/1994
i want display age is 19 years, 6 months, and 9 days
  1. Jeet Verma

    Post:110

    Points:776
    Re: How to calculate age in c#?

    try this code

    ex:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IfExample
    {
      class DateTimeExtensions
      {
      public  string ToAgeString( DateTime dob)
      {
      DateTime dt = DateTime.Now;

      int days = dt.Day - dob.Day;
      if (days < 0)
      {
      dt = dt.AddMonths(-1);
      days += DateTime.DaysInMonth(dt.Year, dt.Month);
      }

      int months = dt.Month - dob.Month;
      if (months < 0)
      {
      dt = dt.AddYears(-1);
      months += 12;
      }

      int years = dt.Year - dob.Year;

      return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
      years, (years == 1) ? "" : "s",
      months, (months == 1) ? "" : "s",
      days, (days == 1) ? "" : "s");
      }

      static void Main()
      {
      DateTimeExtensions obj = new DateTimeExtensions();
      Console.WriteLine("Enter your date of birth in mm/dd/yyyy format to calculate age");
      DateTime dob = DateTime.Parse(Console.ReadLine());
      string s = obj.ToAgeString(dob);
      Console.WriteLine(s);
      Console.ReadLine();
      }
      }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!