C#使用DateTime计算年龄,但给定的出生日期为01-01-0001



目前,我正在尝试计算具有给定生日的人的年龄,但是每当我运行代码时,生日的重构者都会将生日重构转到默认值01-01-0001。

生日在这里设定:

private DateTime BirthDate { get; set; }

这就是我计算人的年龄的方式:

public int Age
    {
        get
        {
            int Age = (int)(DateTime.Today - BirthDate).TotalDays;
            Age = Age / 365;
            return Age;
        }
    }

这是我要使用的生日:

new DateTime(2000, 3, 12)

但是,每当我在Visual Studio中使用调试器时,就会给出生日: 01-01-0001

编辑:这是我使用DateTime的其余代码:这部分在我的主要班级中:

Customer cust = new Customer();
        cust.VoegToe(new Customer("Lionel Messi", new DateTime(2000, 3, 12), new DateTime(2019, 2, 23)));

此部分在我的子类中:

public Customer()
            {
                customers = new List<Customer>();
            }


        public Customer(string name, DateTime BirthDate, DateTime signUpDate)
        {
            this.name = name;
            this.signUpDate = signUpDate;
            this.BirthDate= BirthDate;
        }

有办法解决此问题吗?

预先感谢

我刚刚测试了您提供的代码,它与1个客户效果很好。您遇到的问题可能在列表中,并让班级客户包含客户列表以及您如何访问实例化对象的年龄。

这很好:

    public class Customer
    {
        private string name;
        private DateTime signUpDate;
        public DateTime BirthDate { get; }
        public int Age
        {
            get
            {
                int Age = (int)(DateTime.Today - BirthDate).TotalDays;
                Age = Age / 365;
                return Age;
            }
        }
        public Customer(string name, DateTime BirthDate, DateTime signUpDate)
        {
            this.name = name;
            this.signUpDate = signUpDate;
            this.BirthDate = BirthDate;
        }
    }

使用按钮来计算年龄并显示:

        private void button1_Click(object sender, EventArgs e)
        {
            Customer test = new Customer("Lionel Messi", new DateTime(2000, 3, 12), new DateTime(2019, 2, 23));
            teAge.Text = test.Age.ToString();
        }

如果您想确切发布如何访问年龄的方式,也许我可以为您提供更多帮助。

好吧,您的逻辑存在缺陷。最重要的是,由于它不需要多年。另一件事是,DateTime类为您提供了您所需的一切。

为了使其可测试,显然,您还应该尝试将给定的一天作为参数:

static class AgeCalculator
{
    static int GetAgeInYears(DateTime birth) => GetAgeInYears(brith, DateTime.Today);
    static int GetAgeInYears(DateTime birth, DateTime mes)
    {
        var age = mes.Year - birth.Year - 1;
        // if the birthday already has past (or is today)
        if(birth.Month > mes.Month || (birth.Month == mes.Month && birth.Day => mes.Day)
        {
            age++;
        }
        return age;
    }

更高级的方法是创建一个DateTimeSpan类/结构,该类别还可以跟踪年龄的天数(和或几个月)。但是在大多数情况下,这不是用例的一部分。

最新更新