怎么办我的代码来计算出生日期的年龄?

时间:2017-08-22 17:21:12

标签: c# date date-of-birth

namespace Computerization_of_Health_Records
{
    public class HealthProfile
    {
        //auto implemented property Firstname implicitly creates an 
        //instance variable for the patients first name
        public string FirstName { get; set; }

        //auto implemented property Firstname implicitly creates an 
        //instance variable for the patients last name
        public string LastName { get; set; }

        //auto implemented property Gender implicitly creates an 
        //instance variable for the patients gender
        public string Gender { get; set; }

        //auto implemented property birthday implicitly creates an 
        //instance variable for the patients birth day
        public Int32 Birthday { get; set; }

        //auto implemented property height implicitly creates an 
        //instance variable for the patients height
        public string Height { get; set; }

        //auto implemented property weight implicitly creates an 
        //instance variable for the patients weight
        public string Weight { get; set; }

        public string maxHeartRate { get; set; }

        public string bmi { get; set; }

        public string Age { get; set; }


        //constructor to initialize first name, last name, gender, birthday, birth month,
        //Birth year, height and weight.
        public HealthProfile(string first, string last, string gender, Int32 birthday, string height, string weight, string maxHrtRate)
        {
            FirstName = first;
            LastName = last;
            Gender = gender;
            Birthday = birthday;
            Height = height;
            Weight = weight;
            maxHeartRate = maxHrtRate;
        }


    }



    }

1 个答案:

答案 0 :(得分:1)

以UTC格式将出生日期传递给以下函数(因为它是标准日期格式)。

public static string GetAge(DateTime dob)
{
    DateTime todayDateUtc = DateTime.UtcNow;
    DateTime pastYearDate;
    int years = 0;
    string age;
    int days;

    if(DateTime.UtcNow > dob) {
        years = new DateTime(DateTime.UtcNow.Subtract(dob).Ticks).Year - 1;
    }

    pastYearDate = dob.AddYears(years);
    days = todayDateUtc.Subtract(pastYearDate).Days;
    age = years + " years " + days + " days";

    return age;
}