0

可能重复:
从生日计算年龄

您如何计算年龄,以格式从 TextBox 获取输入dd/MM/yyyy

例如

输入:txtDOB.Text 20/02/1989(字符串格式)
输出:txtAge.Text 23

4

7 回答 7

3

您可以使用( linkSubstract ) 的方法,然后使用属性来确定实际年龄:DateTimeDays

DateTime now = DateTime.Now;
DateTime givenDate = DateTime.Parse(input);

int days = now.Subtract(givenDate).Days
int age = Math.Floor(days / 365.24219)
于 2012-07-30T07:41:09.527 回答
0

正如评论中已经指出的,正确的答案在这里:Calculate age in C#

您只需要将生日作为 DateTime 获取:

DateTime bday = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);
于 2012-07-30T07:40:31.697 回答
0
TimeSpan TS = DateTime.Now - new DateTime(1989, 02, 20);
double Years = TS.TotalDays / 365.25;  // 365 1/4 days per year
于 2012-07-30T07:42:18.777 回答
-1

将出生日期解析为 DateTime 后,以下操作将起作用:

static int AgeInYears(DateTime birthday, DateTime today)
{
    return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
}

像这样解析日期:

DateTime dob = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);

和一个示例程序:

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dob = new DateTime(2010, 12, 30);
            DateTime today = DateTime.Now;

            int age = AgeInYears(dob, today);

            Console.WriteLine(age); // Prints "1"
        }

        static int AgeInYears(DateTime birthday, DateTime today)
        {
            return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
        }
    }
}
于 2012-07-30T07:58:46.850 回答
-1

这个答案不是最有效的,因为它使用循环,但它也不依赖于使用 365.25 幻数。

返回从 adatetime到今天的完整年数的函数:

public static int CalcYears(DateTime fromDate)
    {
        int years = 0;
        DateTime toDate = DateTime.Now;
        while (toDate.AddYears(-1) >= fromDate)
        {
            years++;
            toDate = toDate.AddYears(-1);
        }
        return years;
    }

用法:

int age = CalcYears(DateTime.ParseExact(txtDateOfBirth.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture));
于 2012-07-30T12:09:43.520 回答
-2
var date = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var age = (DateTime.Today.Year - date.Year);
Console.WriteLine(age);
于 2012-07-30T07:43:48.793 回答
-3

尝试这个

string[] AgeVal=textbox.text.split('/');
string Year=AgeVal[2].tostring();
string CurrentYear= DateTime.Now.Date.Year.ToString();
int Age=Convert.ToInt16((Current))-Convert.ToInt16((Year));

减去这两个值并得到你的年龄。

于 2012-07-30T07:43:19.140 回答