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

本文关键字:转换 1岁 出生日期 0岁时 显示 | 更新日期: 2023-09-27 18:05:27

在我的项目中,我正在处理患者流,如果患者只有几天大,那么我的UI只显示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;
    }
}

当1岁以下的出生日期显示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;
        }
    }
}
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,所以您需要减去它来获得实际年龄。