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

时间:2016-04-03 11:45:24

标签: c#

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

我想根据实时计算年龄。例如,如果该人出生于(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);
            }
        }


    }

4 个答案:

答案 0 :(得分:1)

尝试使用TimeSpan

TimeSpan age = (DateTime.Today).Subtract(new DateTime(kidAge.Year, kidAge.Month, kidAge.Day));

我相信这应该有用。

答案 1 :(得分:1)

为了确切年龄,请使用:

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

此函数将返回具有完整年龄的字符串。只需在此函数中设置字符串,如:

var age = ToAgeString();

答案 2 :(得分:1)

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

其次,如果“生日查询”始终只提供一个结果,则可以使用string birthdaystring = (string)cmd.ExecuteScalar()返回单个对象。

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

计算年龄+月数+天的年龄有点棘手。你可以看看Hugo Goncalves的回答。

根据您想要的准确度,您也可以在几天内获得两个日期之间的差异,然后通过除法来估算年份和月份。但这可能会变得非常不准确。

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

答案 3 :(得分:0)

请尝试:

int Age = Convert.ToInt32(today.Year) - Convert.ToInt32(kidAge.Year);

请注意,这只会给出年龄。