如何让我的代码从出生日期计算年龄?
Posted
技术标签:
【中文标题】如何让我的代码从出生日期计算年龄?【英文标题】:How to do i get my code to calculate the age from birthdate? 【发布时间】:2018-01-31 02:11:01 【问题描述】: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;
【问题讨论】:
什么是“TIA”?为什么有这么多与问题无关的代码? 问题中的任何代码与计算生日有什么关系? 你的生日变量是 Int32。除非其中至少包含时间跨度值,否则您将无法计算年龄。 您的代码中没有出生日期,并且您已经指定了年龄。请更正问题以使其合理并减少不需要的代码量。情况很混乱。 使用一些常识。如果您使用铅笔和纸手动计算某人的年龄,您将如何计算?弄清楚并写下步骤。然后将这些步骤转换为代码。如果您在将任何步骤转换为代码时遇到问题,请询问有关该步骤的问题。 【参考方案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;
【讨论】:
以上是关于如何让我的代码从出生日期计算年龄?的主要内容,如果未能解决你的问题,请参考以下文章