C#将生日日期转换为年龄

C#将生日日期转换为年龄,c#,C#,生日是我数据库中的一个字符串,其格式类似于今年/月/日 我想实时计算年龄。例如,如果此人出生于(2015/5/1),则其年龄应为1岁,根据日期的不同,可以是1个月、1年、1天、7年。。等 我打了这个标记/*以显示我想转换年龄的位置 这是我的代码,但帮不了什么忙 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.W

生日是我数据库中的一个字符串,其格式类似于今年/月/日

我想实时计算年龄。例如,如果此人出生于(2015/5/1),则其年龄应为1岁,根据日期的不同,可以是1个月、1年、1天、7年。。等

我打了这个标记/*以显示我想转换年龄的位置

这是我的代码,但帮不了什么忙

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.SqlClient;
    using System.Data;
    using System.Configuration;
    using System.Data.Odbc;
    using System.Data.OleDb;

    public partial class Reg : Page
    {
        protected void GO_Click(object sender, EventArgs e)
        {
            string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\db.mdb;Persist Security Info=True";
            OleDbConnection myConnection;
            OleDbCommand cmd;


            try
            {


                // Open OleDb Connection
                myConnection = new OleDbConnection();
                myConnection.ConnectionString = myConnectionString;
                myConnection.Open();

                // Execute Queries
                cmd = myConnection.CreateCommand();

                //---------------------------
                int d = Convert.ToInt32(T7.Text);
                int m = Convert.ToInt32(T6.Text);
                int y = Convert.ToInt32(T5.Text);
                string D = Convert.ToString(d);
                string M = Convert.ToString(m);
                string Y = Convert.ToString(y);
                string n = T1.Text ,CID=T9.Text,FID=T8.Text;
                string l = T2.Text;
                string v = T4.Text,type= D1.SelectedItem.ToString();
                string age = Y + "/" + M + "/" + D;


                //---------------------------

                cmd.CommandText = "SELECT count(*) FROM Visitor where CID ='" +CID + "' and FID ='" + FID + "'";


                int temp ;
                    temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
                Response.Write(temp);


                if (temp == 1)
                {
                    //getting the kid age 

                    string kidAge= cmd.CommandText = "SELECT age FROME Visitor WHERE  CID ='" + CID + "' and FID='" + FID + "' ";

// here my problem trying to conver kidAge to his real age maybe it 10year or something    
                /*    DateTime today = DateTime.Today;

                    int Age = today.Year - kidAge.Year;

                    if (bday > today.AddYears(-age))
                        age--;

                    cmd.ExecuteNonQuery();

                 */
   // get the right vassile for kid depending in age it may be for 1 year ..etc
                    string Vassl = cmd.CommandText = "SELECT * FROM [Activating inoculation] where IID='"+ kidAge + "'";
                    cmd.ExecuteNonQuery();

                    // get nearst date for vassile
                    string AppDate = cmd.CommandText = "SELECT * FROM VassileAppointments where IID";
                    //updating
                    cmd.CommandText = "UPDATE Visitor SET  Vphone ='" + v + "' where CID ='" + CID + "' and FID='" + FID + "' ";
                    cmd.ExecuteNonQuery();
                    // appointment
                    DateTime ReqDate = DateTime.Today;
                    cmd.CommandText = "INSERT INTO [Visitor Appointment] Type ='" + type + "', ReqDate ='"+ReqDate+"' ,AppointmentDate='" + AppDate + "' VID='" + CID + "'";
                    cmd.ExecuteNonQuery();
                    Response.Write(" تم  تسجيل الموعد");
                }    
                    else 
                    {
                    //works cmd INSERT  cmd.CommandText = "INSERT INTO Visitor (FName,LName,age,Vphone) VALUES ('" + n + "','" + l + "','" + age + "','" + v + "')";

                    cmd.CommandText = "INSERT INTO Visitor (FName,LName,age,Vphone) VALUES ('" + n + "','" + l + "','" + age + "','" + v + "')";
                    cmd.ExecuteNonQuery();


                    Response.Write("تم تسجيل الموعد والبيانات");


                }
        }

            catch (Exception ex)
            {
                Response.Write("OLEDB Connection FAILED: " + ex.Message);
            }
        }


    }
请尝试:

int Age = Convert.ToInt32(today.Year) - Convert.ToInt32(kidAge.Year);
请注意,这只会给出以年为单位的年龄。

尝试使用library

我相信这应该有效。

要获得准确的年龄,请使用:

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

    int days = dt.Day - dob.Day;
    if (days < 0)
    {
        dt = dt.AddMonths(-1);
        days += DateTime.DaysInMonth(dt.Year, dt.Month);
    }

    int months = dt.Month - dob.Month;
    if (months < 0)
    {
        dt = dt.AddYears(-1);
        months += 12;
    }

    int years = dt.Year - dob.Year;

    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");
}

首先:您不应该使用字符串连接创建查询,因为这将导致SQL注入。改用参数化查询

其次,如果“生日查询”总是只给出一个结果,那么可以使用
string birthdaystring=(string)cmd.ExecuteScalar()
返回单个对象

可以通过
DateTime birthday=DateTime.Parse(birthdaystring)
将字符串转换为日期。您可能必须根据您的区域设置和数据库中日期的格式定义FormatProvider

那么,以年+月+日来计算年龄就有点棘手了。你可以看看雨果·冈卡尔维斯的答案

根据你想要的准确度,你也可以得到两个日期之间的差值,以天为单位,然后除以年和月。但这可能变得相当不准确

TimeSpan age = DateTime.Now.Date - birthday;
var totalmonths = age.TotalDays / 30; //
var years = totalmonths / 12;
var month = totalmonths % 12; 

如果今天是4月3日,a生日是12月12日,则不会给出正确的结果。是的,如果按年份给出,则仅对第七年有效。“今天”
kidAge
是一个字符串。看到评论,我猜OP在转换为
DateTime
时遇到问题,应该有人建议
DateTime.Parse
ParseExact
。使用参数。请看网页:这个问题,正如你所说的,并不像看上去那么琐碎。你如何定义你的年、月等。?日历年/月?如果是这样,确定一个人的年龄(以日历年为单位)并不是一项简单的任务:您需要考虑闰年、一个月的天数等:这也可能因所使用的文化和/或日历而异。所以你真的需要非常清楚地说明这个问题:你想要的结果是什么?做一个输入和输出的示例,然后告诉我。是的,TimeSpan课程是一个不错的选择。遗憾的是,TimeSpan中最大的单位是天。因此,要以月或年为单位计算年龄,你必须进行额外的处理。你是对的,但一旦你有了一个TimeSpan实例,就只需要额外的一码就可以得到年/十年/等等。@asafSavich事实上,如果你想准确地计算年、月和日是相当棘手的。@derpirscher我同意这不是直观的,但是有一些非常好的建议。比如一个
var age = ToAgeString();
TimeSpan age = DateTime.Now.Date - birthday;
var totalmonths = age.TotalDays / 30; //
var years = totalmonths / 12;
var month = totalmonths % 12;