How to Calculate Age in C#

This comes tricky when calculating someones age in C# because there is lot of methods and we don’t know which is the best way to calculate age in C#, So here is some methods to calculate someones age in C#.

In the example, we have the current date and the dob and with a button click it displays the age in a label.
age calc

Method 1

calculate age c sharp code
DateTime today = DateTime.Today;
DateTime Dob = dtpDob.Value;
int age = today.Year - Dob.Year;
if (Dob > today.AddYears(-age)) age--;
lblAge.Text = age.ToString();

Method 2

calculate age c sharp code
DateTime Dob = dtpDob.Value;
var now = float.Parse(DateTime.Now.ToString("yyyy.MMdd"));
var dobyear = float.Parse(Dob.ToString("yyyy.MMdd"));
var age = (int)(now - dobyear);
lblAge.Text = age.ToString();


Please enter your comment!
Please enter your name here