Retrieving Year and calculating difference

  • Thread starter Thread starter RP
  • Start date Start date
R

RP

I have a date entered in a TextBox. On this TextBox LostFocus, I want
to retrieve the year part and then calculate the difference from
current year.
 
RP said:
Did something like this:

--------------------------------------------------------------------
DateTime myDate = txtDOB.Text;
int myYear = myDate.Year;
int PresentYear = DateTime.Now.Year;
txtAge.Text = (PresentYear - myYear);

What about the code doesn't do what you want?

The one thing that jumps out to me is that if you are really looking for
a calculation of "age", then the above doesn't take into account the
rest of the date. Is that your concern?

If so, then something like this might work for you:

DateTime myDate = DateTime.Parse(txtDOB.Text),
dateNow = DateTime.Now;
int cyearsAge = dateNow.Year - myDate.Year;

myDate = myDate.AddYears(cyearsAge);
if (myDate > dateNow)
{
cyearsAge--;
}

txtAge.Text = cyearsAge.ToString();

Pete
 
Did something like this:

--------------------------------------------------------------------
DateTime myDate = txtDOB.Text;
int myYear = myDate.Year;
int PresentYear = DateTime.Now.Year;
txtAge.Text = (PresentYear - myYear);

Of course it depends on your definition for a year. How will the code
handle a situation like 1 Jan 2007 and 31 Dec 2007? Personally I'd do
the following:

DateTime myDate = DateTime.Parse(txtDOB.Text);
TimeSpan interval = myDate - DateTime.Now
decimal years = interval.Days / 365

In this case years will have a pretty good representation of elasped
years, which you can then decide to round up depending on the level of
accuracy you want. So 0.999 could be pushed up to 1.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top