Returns the age at the current date. - CSharp System

CSharp examples for System:DateTime Calculate

Description

Returns the age at the current date.

Demo Code

// Copyright by the Spark Development Network
using System;/*from w  w w  .j  a  v a 2 s .co  m*/

public class Main{
        /// <summary>
        /// Returns the age at the current date.
        /// </summary>
        /// <param name="start"></param>
        /// <returns></returns>
        public static int Age( this DateTime start )
        {
            var now = RockDateTime.Today;
            int age = now.Year - start.Year;
            if ( start > now.AddYears( -age ) ) age--;

            return age;
        }
        #region DateTime Extensions

        /// <summary>
        /// Returns the age at the current date.
        /// </summary>
        /// <param name="start"></param>
        /// <returns></returns>
        public static int Age( this DateTime? start )
        {
            if ( start.HasValue )
                return start.Value.Age();
            else
                return 0;
        }
}

Related Tutorials