Age Calculator in C# (Years + Months + Days) – Programming, Pseudocode Example, C# Programming Example
C# C# Console

Age Calculator in C# (Years + Months + Days)

Calculate the age of a person from 2 DateTime is a problem that is often found in programming and also in C #.
Here is a solution that allows you to easily and simply calculate someone’s age in C #.

Here is the C # solution to calculate the age of a person with DateTime.
DateTime represents moments (like the timestamp), they can sometimes seem complicated to handle to do simple things but we learn very quickly to master them and not to do without them.

The details of the C # lines:

C # 1: we initialize a DateTime to retrieve today’s date (today) and not have to rewrite DateTime.Today in the following lines.

C # 2: we calculate an “age” by subtracting the year of the birthday from the current year.
The age you get at this level will not always be good.
Imagine that it is March 10, 2011 and we want to calculate in C # the age of a person born on July 7, 2000
Current year – Anniversary year = 2011 – 2000 = 11
While the person will not be 11 years old until July 7, 2011
The last C # line is there to correct the problem

C # 3: if the birthday is higher (after) the current date minus the age, we withdraw 1 year.
Example: The Datetime of the birthday: July 7, 2000 is actually larger than the current date – age = March 10, 2011 – 11 = March 10, 2000
07/07/2000> 03/10/2000 so we withdraw 1 year, which gives us an age of 10 years.

We can then do a function that calculates the age in C # for us and that takes a DateTime (birthday) as a parameter.



Calculate Age in C# (Years,Months,Days)


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: