C# 如何制作年龄计算器?

C# 如何制作年龄计算器?,c#,windows,console,console-application,windows-console,C#,Windows,Console,Console Application,Windows Console,我做了一个非常简单(不准确)的程序来计算你的年龄。我想通过计算闰年,并考虑到每个月有不同的天数,使之准确。 有什么帮助吗?怎么做?从哪里开始? 谢谢 我的建议如下: public static string ToAgeString(this DateTime dob) { DateTime today = DateTime.Today; int months = today.Month - dob.Month; int years = today.Year - dob.

我做了一个非常简单(不准确)的程序来计算你的年龄。我想通过计算闰年,并考虑到每个月有不同的天数,使之准确。 有什么帮助吗?怎么做?从哪里开始? 谢谢


我的建议如下:

public static string ToAgeString(this DateTime dob)
{
    DateTime today = DateTime.Today;

    int months = today.Month - dob.Month;
    int years = today.Year - dob.Year;

    if (today.Day < dob.Day)
    {
        months--;
    }

    if (months < 0)
    {
        years--;
        months += 12;
    }

    int days = (today - dob.AddMonths((years * 12) + months)).Days;

    return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
                         years, (years == 1) ? "" : "s",
                         months, (months == 1) ? "" : "s",
                         days, (days == 1) ? "" : "s");
}
publicstaticstringtoagesting(此日期时间dob)
{
DateTime today=DateTime.today;
int months=今天.Month-月日.Month;
int YERS=今日年-年月日;
如果(今天<月日)
{
月--;
}
如果(月数<0)
{
年--;
月数+=12;
}
整数天=(今天-月加月份((年*12)+月))。天;
返回string.Format(“{0}年{1},{2}月{3}和{4}日{5}”,
年,(年=1)?“”:“s”,
月数,(月=1)?“”:“s”,
天(天=1)?“”:“s”);
}
public static string ToAgeString(this DateTime dob)
{
    DateTime today = DateTime.Today;

    int months = today.Month - dob.Month;
    int years = today.Year - dob.Year;

    if (today.Day < dob.Day)
    {
        months--;
    }

    if (months < 0)
    {
        years--;
        months += 12;
    }

    int days = (today - dob.AddMonths((years * 12) + months)).Days;

    return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
                         years, (years == 1) ? "" : "s",
                         months, (months == 1) ? "" : "s",
                         days, (days == 1) ? "" : "s");
}