We calculate our age by getting the difference in full years between the current date and our date of birth. This number indicates the age at which we are born. In this post, we will learn how to calculate the age of someone based on his birthday date.
How to Calculate the Age Based on Birthday Date in C#
int age = 0;
int days = DateTime.Now.Subtract(birthdate).Days;
age = days / 365;
This will return the exact age as integer.
You can use the following code if you just want the number of years without the decimal digit:
// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// In case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;
How to Calculate the Age Based on Birthday Date in SQL
Here is a simple SQL statement to calculate the age of someone using SQL:
DECLARE @birthdate AS Date = CONVERT(date, '1975-08-25')
Select DATEDIFF(MONTH,@birthdate, GETDATE())/12.0 -
(Case WHEN MONTH(@birthdate)=MONTH(GETDATE())
AND DAY(@birthdate) > DAY(GETDATE()) THEN 1 ELSE 0 END)
AS Age
In this post, we have learned how to calculate the age of a person from the date of birth by using C# and SQL.