Library code snippets
Calculate Age
By James Crowley, published on 20 Feb 2005
Calculating someone's age is pretty straightforward, and here's how! In order for the code to work, you need a DateTime object called BirthDate containing the birthday.
C#
// get the difference in years
int years = DateTime.Now.Year - BirthDate.Year;
// subtract another year if we're before the
// birth day in the current year
if (DateTime.Now.Month < BirthDate.Month ||
(DateTime.Now.Month == BirthDate.Month &&
DateTime.Now.Day < BirthDate.Day))
years--;
VB.NET
' get the difference in years
Dim years As Integer = DateTime.Now.Year - BirthDate.Year
' subtract another year if we're before the
' birth day in the current year
If DateTime.Now.Month < BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day < BirthDate.Day) Then
years = years - 1
End If
Related articles
Related discussion
-
hey developers out there
by pitsophera (0 replies)
-
How can i develop opc server using .net?
by vairajaig (1 replies)
-
Creating a Windows Service in VB.NET
by davidvanr (108 replies)
-
High-Performance .NET Application Development & Architecture
by Manjot Bawa (0 replies)
-
An Introduction to VB.NET and Database Programming
by carlosmen (14 replies)
Related podcasts
-
A Practical Look at Silverlight 2 Part 1
Now that Silverlight 2 is at the Olympics and making a big splash, we wanted to explore this fascinating technology more. Microsoft Silverlight 2 is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive ap...
Events coming up
-
Nov
18
15 Minutes of Fame
Dresher, United States
This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.
Alternative solution:
DateTime comparisonDate = new DateTime(_birthday.Year, DateTime.Now.Month, DateTime.Now.Day);
int age = (comparisonDate.Date < _birthday.Date) ?DateTime.Now.Year - _birthday.Year - 1:
DateTime.Now.Year - _birthday.Year;
Description of calculate age and working principle
This thread is for discussions of Calculate Age.