Monday, July 29, 2019

c# Function CalculateYourAge

  1. public static string CalculateYourAge(DateTime Dob)    
  2.        {    
  3.            DateTime Now = DateTime.Now;    
  4.            int _Years = new DateTime(DateTime.Now.Subtract(Dob).Ticks).Year - 1;    
  5.            DateTime _DOBDateNow = Dob.AddYears(_Years);    
  6.            int _Months = 0;    
  7.            for (int i = 1; i <= 12; i++)    
  8.            {    
  9.                if (_DOBDateNow.AddMonths(i) == Now)    
  10.                {    
  11.                    _Months = i;    
  12.                    break;    
  13.                }    
  14.                else if (_DOBDateNow.AddMonths(i) >= Now)    
  15.                {    
  16.                    _Months = i - 1;    
  17.                    break;    
  18.                }    
  19.            }    
  20.            int Days = Now.Subtract(_DOBDateNow.AddMonths(_Months)).Days;      
  21.                
  22.            return $"Age is {_Years} Years {_Months} Months {Days} Days";    
  23.        }   

No comments:

Post a Comment