当1岁以下的出生日期显示0岁时,我想将其转换为数月和数日

时间:2014-05-28 11:49:44

标签: c# datetime

在我的项目中,我正在开展患者流程,如果病人只有几天大,那么我的用户界面只显示0岁而不是,例如2天或6个月。

我希望将此逻辑用于计算患者月数和天数的年龄。

下面是我用于计算患者年龄的C#函数:

public int CalculatedAge
{
    get
    {
        if (Patient.DateOfBirth == null && !Patient.Age.HasValue)
            return 0;
        else if (Patient.DateOfBirth == null && Patient.Age != null && Patient.Age.HasValue)
            return Patient.Age.Value;
        else if (Patient.DateOfBirth != null)
            return DateTime.Now.ToUniversalTime().Year - Patient.DateOfBirth.Value.Year;
        return 0;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以创建新实体。

enum AgeUnits
{
    Days,
    Months,
    Years
}

class Age
{
    public int Value { get; private set; }
    public AgeUnits Units { get; private set; }

    public Age(int value, AgeUnits ageUnits)
    {
        Value = value;
        Units = ageUnits;
    }
}

然后,您可以使用Age作为CalculatedAge属性的类型。

public Age CalculatedAge
{
    get
    {
        if (Patient.DateOfBirth.HasValue)
        {
            DateTime bday = Patient.DateOfBirth.Value;
            DateTime now = DateTime.UtcNow;
            if (bday.AddYears(1) < now)
            {
                int years = now.Year - bday.year;
                if (bday > now.AddYears(-years))
                    years--;
                return new Age(years, AgeUnits.Years);
            }
            else if (bday.AddMonths(1) < now)
            {
                int months = (now.Months - bday.Months + 12) % 12;
                if (bday > now.AddMonths(-months))
                    months--;
                return new Age(months, AgeUnits.Months);
            }
            else
            {
                int days = (now - bday).Days;
                return new Age(days, AgeUnits.Days);
            }
        }
        else
        {
            if (Patient.Age.HasValue)
                return new Age(Patient.Age.Value, AgeUnits.Years);
            else
                return null;
        }
    }
}

答案 1 :(得分:0)

public Age CalculatedAge
{
    get
    {
        if (Patient.DateOfBirth == null && Patient.Age != null && Patient.Age.HasValue)
            return new Age(Patient.Age.Value);
        else if (Patient.DateOfBirth != null)
        {
            DateTime now = DateTime.UtcNow;
            TimeSpan tsAge = now - Patient.DateOfBirth;
            DateTime age = new DateTime(tsAge.Ticks);
            return new Age(age.Year - 1, age.Month - 1, age.Day - 1);
        }
        return new Age(0);
    }
}

这是Age结构:

struct Age
{
    public int Years, Months, Days; //It's a small struct, properties aren't necessary
    public Age(int years, int months = 0, int days = 0) { this.Years = years; this.Months = months; this.Days = days; }
}

显然,您可以使用IF语句检查值,但在我看来,为此目的的结构更清晰。 return new Age(age.Year - 1, age.Month - 1, age.Day - 1);这部分原因是DateTime对象的MinValue01/01/0001,因此您需要减去它以获得真实年龄。