Benny Sutton is 4 hire - just click here

Extension method to get the age in years

Need to work out the lapsed time in years between a date and now? This is how!

           
        public static int CalculateAge(this DateTime dateTime)
        {
            var age = DateTime.Now.Year - dateTime.Year;
            if (DateTime.Now < dateTime.AddYears(age))
                age--;
            return age;
        }
   
    

Extension methods are easy to chain, simply call like this...

         
         int years = DateTime.Now.CalculateAge();