【问题标题】:How to calculate an age based on a birthday [duplicate]如何根据生日计算年龄[重复]
【发布时间】:2023-03-14 01:27:01
【问题描述】:

可能重复:
How do I calculate someone's age based on a DateTime type birthday?

我想编写一个 ASP.NET 辅助方法,该方法返回一个人的年龄(给定他或她的生日)。

我试过这样的代码:

public static string Age(this HtmlHelper helper, DateTime birthday)
{
    return (DateTime.Now - birthday); //??
}

但它不起作用。根据生日计算人员年龄的正确方法是什么?

【问题讨论】:

    标签: c# asp.net-mvc date-arithmetic


    【解决方案1】:

    我真的不明白你为什么要把它设为 HTML Helper。我会将其作为控制器操作方法中 ViewData 字典的一部分。像这样的:

    ViewData["Age"] = DateTime.Now.Year - birthday.Year;
    

    假设生日被传递到一个动作方法中并且是一个 DateTime 对象。

    【讨论】:

    • 如果有人出生在'2009-12-31',则不起作用;在'2010-01-01' 已经有一年了?
    • 如前所述,如果这个人在一月一日出生,那总是正确的。在任何其他情况下,如果当前月/日不在生日的月/日之后,则结果会出现错误。
    【解决方案2】:

    Stack Overflow 使用这样的函数来确定用户的年龄。

    How do I calculate someone's age based on a DateTime type birthday?

    给出的答案是

    DateTime now = DateTime.Today;
    int age = now.Year - bday.Year;
    if (now < bday.AddYears(age)) 
        age--;
    

    所以你的辅助方法看起来像:

    public static string Age(this HtmlHelper helper, DateTime birthday)
    {
        DateTime now = DateTime.Today;
        int age = now.Year - birthday.Year;
        if (now < birthday.AddYears(age)) 
            age--;
    
        return age.ToString();
    }
    

    今天,我使用此函数的不同版本来包含参考日期。这让我可以得到某人在未来某个日期或过去的年龄。这用于我们的预订系统,需要未来的年龄。

    public static int GetAge(DateTime reference, DateTime birthday)
    {
        int age = reference.Year - birthday.Year;
        if (reference < birthday.AddYears(age))
            age--;
    
        return age;
    }
    

    【讨论】:

    • 为什么不只是new DateTime(DateTime.Now.Subtract(birthDate.Ticks).Year - 1
    • 在旁注中,未来生日的正确行为是什么?返回负数?扔?另外,昨天出生的人的年龄是0岁吗?
    • @Steven 尚未出生的人的年龄应该始终为 0,imo。到那年年底,你只有 1 年。这与 y2k 上发生的辩论相同。我们庆祝了日期的变化,但 2000 年仅在 2001 年初完成,所以我们应该在 2001 年初庆祝 2000 年,而不是在 2000 年初。
    • 也许如果我们想为未来的出生返回 0,我们可以这样做:return (new DateTime(Math.Max(0, DateTime.Now.Substract(birthDate.Ticks)).Year - 1)
    • 有些文化将婴儿生命的第一年视为第一年。
    【解决方案3】:

    我是这样做的:

    (代码略短)

    public struct Age
    {
        public readonly int Years;
        public readonly int Months;
        public readonly int Days;
    
    }
    
    public Age( int y, int m, int d ) : this()
    {
        Years = y;
        Months = m;
        Days = d;
    }
    
    public static Age CalculateAge ( DateTime birthDate, DateTime anotherDate )
    {
        if( startDate.Date > endDate.Date )
            {
                throw new ArgumentException ("startDate cannot be higher then endDate", "startDate");
            }
    
            int years = endDate.Year - startDate.Year;
            int months = 0;
            int days = 0;
    
            // Check if the last year, was a full year.
            if( endDate < startDate.AddYears (years) && years != 0 )
            {
                years--;
            }
    
            // Calculate the number of months.
            startDate = startDate.AddYears (years);
    
            if( startDate.Year == endDate.Year )
            {
                months = endDate.Month - startDate.Month;
            }
            else
            {
                months = ( 12 - startDate.Month ) + endDate.Month;
            }
    
            // Check if last month was a complete month.
            if( endDate < startDate.AddMonths (months) && months != 0 )
            {
                months--;
            }
    
            // Calculate the number of days.
            startDate = startDate.AddMonths (months);
    
            days = ( endDate - startDate ).Days;
    
            return new Age (years, months, days);
    }
    
    // Implement Equals, GetHashCode, etc... as well
    // Overload equality and other operators, etc...
    

    }

    【讨论】:

      【解决方案4】:

      ancient thread 的另一种巧妙方法:

      int age = (
          Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
          Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-31
        • 1970-01-01
        • 2019-08-12
        • 2014-04-04
        • 2021-08-21
        • 1970-01-01
        • 2020-09-25
        相关资源
        最近更新 更多