Thursday 4 April 2013

Calculate your age

Hi Big,

Many times I found myself to write code to  calculate age. So here it is:



  public static void CalculateYourAge(DateTime currentDate, DateTime? dob,out int year,out int month,out int day)
        {
            year = 0;
            month = 0;
            day = 0;
            if (dob != null)
            {
                DateTime dateOfBirth;
             
                DateTime.TryParse(dob.Value.ToShortDateString(), out dateOfBirth);
               

                TimeSpan difference = currentDate.Subtract(dateOfBirth);
                DateTime age = DateTime.MinValue + difference;
                 year = age.Year - 1;
                 month = age.Month - 1;
                 day = age.Day - 1;
            }
        }

No comments:

Post a Comment