Home > DeveloperSection > Forums > How to calculate age in c#?
john rob

Total Post:108

Points:756
Posted on    October-26-2014 11:59 PM

 C# C# 
Ratings:


 1 Reply(s)
 709  View(s)
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


Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    October-27-2014 12:01 AM

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();
  }
  }
}

Don't want to miss updates? Please click the below button!

Follow MindStick