簡體   English   中英

c# 使用日期時間計算年齡,但給定的生日是 01-01-0001

[英]c# calculating age using datetime but the given birthdate goes to 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 個客戶運行良好。 您遇到的問題可能與列表有關,並且讓類 Customer 包含客戶列表以及您如何訪問實例化對象的年齡。

這工作得很好:

    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類/結構,它還可以跟蹤年齡的天數(和或月數)。 但在大多數情況下,這不是用例的一部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM