P5: Calculate Age
Age Calculator Program
Explanation
The program prompts the user to enter their birthdate in a specific format ("yyyy-MM-dd").
It uses
DateTime.ParseExact
to convert the string input into aDateTime
object. This method is chosen to ensure the format is strictly adhered to.The age is initially calculated by subtracting the birth year from the current year.
There's an additional check to adjust the age if the current date hasn't reached the user's birthday in the current year. This is important for accuracy.
Finally, the calculated age is displayed.
This program is a practical demonstration of using the DateTime
class in C#. It covers parsing string input to DateTime
, manipulating dates, and basic arithmetic with date components.
Last updated