如何计算从日期开始的年龄

Rif*_*han 0 c# asp.net datetime

我看到这已被问过很多次了.很多人都回答了,但我还没能让它发挥作用.

这是我从搜索中得到的代码:

public static int CalculateAge(DateTime birthDate)
{
    DateTime now = DateTime.Today;
    int years = now.Year - birthDate.Year;

    if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
        --years;

    return years;
}
Run Code Online (Sandbox Code Playgroud)

如何从TextBox提供出生日期?

我使用Jquery日历以dd-mm-yy格式将日期提供给TextBox3 ..

现在我想从提供的日期计算年龄,然后点击按钮保存在数据库中..

我得到了DB部分的保存,但是如何将TextBox值插入上面的代码中,然后使用years将其保存在我的按钮点击事件上?

Son*_*nül 5

所以在这里,我如何从TextBox提供出生日期?

随着供应,如果你的意思是得到它的Text作为DateTime,你可以分析它DateTime喜欢;

DateTime dt;
if(DateTime.TryParseExact(TextBox3.Text, "dd-MM-yy",
                          CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
   // now you can use dt with subtract process as a DateTime
}
Run Code Online (Sandbox Code Playgroud)

或者,如果dd-MM-yy格式是标准的日期和时间格式为你CurrentCulture,你可以直接使用DateTime.Parse()方法等;

var dt = DateTime.Parse(TextBox3.Text);
Run Code Online (Sandbox Code Playgroud)

顺便说一句,mm说明符是几分钟,MM是几个月.不要忘记添加System.Globalization命名空间以使用它们.

另请阅读:计算C#中的年龄