Find out age from given date in C#

It’s really simple. Just follow the code

private void dateTimePicker1_ValueChanged(object sender, EventArgs e) {
   DateTime SD = DateTime.Parse(dateTimePicker1.Text);
   DateTime DOB = new DateTime(SD.Year,SD.Month,SD.Day);
   int y = 0, m = 0, d = 0;
   FindAge(DOB, out y, out m, out d);
   label1.Text = "Year: " + y.ToString() + "\n Month: " + m.ToString() + "\n Day: " + d.ToString();
}

private void FindAge(DateTime DOB, out int y, out int m, out int d) {
   DateTime CD = DateTime.Now;
   y = CD.Year - DOB.Year;
   m = CD.Month - DOB.Month;
   d = CD.Day - DOB.Day;

   if(d < 0) {
      d+= DateTime.DaysInMonth(DOB.Year, DOB.Month);
      m--;
   }
   if(m < 0){
      m+=12;
      y--;
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s