In C#, how do I calculate someone's age based on a DateTime type birthday?

后端 未结 30 2117
名媛妹妹
名媛妹妹 2020-11-21 05:14

Given a DateTime representing a person\'s birthday, how do I calculate their age in years?

30条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 05:40

    I have created a SQL Server User Defined Function to calculate someone's age, given their birthdate. This is useful when you need it as part of a query:

    using System;
    using System.Data;
    using System.Data.Sql;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;
    using Microsoft.SqlServer.Server;
    
    public partial class UserDefinedFunctions
    {
        [SqlFunction(DataAccess = DataAccessKind.Read)]
        public static SqlInt32 CalculateAge(string strBirthDate)
        {
            DateTime dtBirthDate = new DateTime();
            dtBirthDate = Convert.ToDateTime(strBirthDate);
            DateTime dtToday = DateTime.Now;
    
            // get the difference in years
            int years = dtToday.Year - dtBirthDate.Year;
    
            // subtract another year if we're before the
            // birth day in the current year
            if (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day))
                years=years-1;
    
            int intCustomerAge = years;
            return intCustomerAge;
        }
    };
    

提交回复
热议问题