1

The birthday is a string inside my database and it is formatted like this Year/month/day

I want to calculate the age depending in the real time. For example, if the person was born on (2015/5/1) he should be age 1 year , and, depending in the date it can be 1 month , 1 year ,1 day, 7 year .. etc

I putted this mark /* to show where I want to convert the age

here This is my code but it won't help a lot

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


    }
Jongware
  • 22,200
  • 8
  • 54
  • 100
  • Use parameters. See webpage : https://msdn.microsoft.com/en-us/library/yy6y35y8(v=vs.110).aspx – jdweng Apr 03 '16 at 11:55
  • This question, as you specified it, is not that trivial as it may seem. How do you define your years, months, etc.? As calendar years/months? If so, determining how many years and months old a person is (in calendar years), is not a trivial task: you need to account for leap years, days in a month, etc.: this may also vary depending on the used culture and/or calendar. So you really need to specify this question very clearly: what is the result that you want? Make a sample input and output – Jcl Apr 04 '16 at 16:30

4 Answers4

1

Try using TimeSpan library

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

I believe this should work.

Asaf Savich
  • 623
  • 1
  • 9
  • 29
  • 1
    Beat me to it. Yes the TimeSpan class is the way to go. – Wobbles Apr 03 '16 at 11:57
  • Sadly, the biggest unit in timespan is days. So to get the age in month or years you have to do additional processing. – derpirscher Apr 03 '16 at 12:02
  • You right, but once you have a TimeSpan instance, it's only an extra yard to take to get years/decades/etc.. – Asaf Savich Apr 03 '16 at 12:04
  • @asafSavich In fact, getting the years, months and days is quite tricky if you want to do it exactly. – derpirscher Apr 03 '16 at 12:08
  • @derpirscher I agree it's not intuitive, but there are some really good suggestions. Such as [this](http://stackoverflow.com/a/1925560/3434672) one – Asaf Savich Apr 03 '16 at 12:11
  • @asafsavich Getting the exact amount of years, months and days from a timespan in impossible, if you do not have a base date. Consider a timespan of exactly 30 days: It could be 1 month and 2 days (if you start on Feb 1st in a nonleap year), 1 month and 1 day (if you start on Feb 1st in a leap year), exactly 1 month (if you start on April 1st) or not even a complete month (if you start on Jan 1st) – derpirscher Apr 03 '16 at 12:29
  • i try it but it show error :String don't contain a defining of Year , Day , Month – khadija alqatifie Apr 04 '16 at 07:48
  • `TimeSpan age = (DateTime.Today).Subtract(new DateTime(kidAge.Year, kidAge.Month, kidAge.Day));` – Asaf Savich Apr 04 '16 at 09:09
  • `kidAge` is a string. Seeing the comments, I guess the OP has problems converting to a `DateTime`, someone should suggest `DateTime.Parse` or `ParseExact`. – Jcl Apr 04 '16 at 16:39
1

For accurate age, use:

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

This function will return a string with the complete age. Just set your string from this function like:

var age = ToAgeString();
1

First of all: You should not create your queries with string concatenation, as this will lead to SQL injection. Use parametrized queries instead.

Second, if the the "birthday query" always only gives one result, you could use string birthdaystring = (string)cmd.ExecuteScalar() which returns a single object.

Converting the the string to a Date can be done via DateTime birthday = DateTime.Parse(birthdaystring). You may have to define an FormatProvider depending on your locale and the format of the date in the database.

Calculating the age in years + months + days is a bit tricky then. You may have a look at Hugo Goncalves' answer.

Depending on the accuracy you want, you can also just get the difference between the two Dates in days and then approximate years and month by dividing. But this may become quite inaccurate.

TimeSpan age = DateTime.Now.Date - birthday;
var totalmonths = age.TotalDays / 30; //
var years = totalmonths / 12;
var month = totalmonths % 12; 
derpirscher
  • 14,418
  • 3
  • 18
  • 35
0

Please try:

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

Note that, this will only give the age in years.