计算C#中的年龄[重复项]

问题描述 投票:1回答:3

有人可以帮我写一些代码,根据出生年月日来计算特定日期的年龄。

我正在数据库中捕获出生日期和诊断日期,并想通过诊断日期来计算年龄(以年为单位)。

partial void AgeAtDiagnosis_Compute(ref string result)
    {
        // Set result to the desired field value

    }
c# linq ado.net ado.net-entity-data-model
3个回答
2
投票
DateTime birth = new DateTime(1950, 01, 01);
DateTime diagnosis = new DateTime(2012, 02, 01);
TimeSpan Span = diagnosis - birth;
DateTime Age = DateTime.MinValue + Span;
// note: MinValue is 1/1/1 so we have to subtract...
int Years = Age.Year - 1;

1
投票
TimeSpane age0 = this.DateOfDiagnosis - this.DateOfBirth;

int age1 = (int) Math.Trunc( age0.TotalDays / 365.25);

0
投票

您可以从另一个日期中减去一个日期来指定时间跨度。那有一个TotalDays属性,您可以从中得出年份。这取决于您想要达到的精度:

var ageInDays = (diagnoticDate - dateOfBirth).TotalDays;  
var age = Convert.ToInt32(ageInDays / 365);

显然leap年会引起问题,所以另一种选择是检查每个日期的年,月和日属性,并考虑部分年份等,分别计算它们的差异

© www.soinside.com 2019 - 2024. All rights reserved.