P5: Calculate Age

Age Calculator Program

using System.Globalization;

Console.Write("Enter your birthdate (format yyyy-MM-dd): ");
string input = Console.ReadLine();

DateTime birthdate;
bool isValidDate = DateTime.TryParseExact(
    input, 
    "yyyy-MM-dd", 
    null, 
    DateTimeStyles.None, 
    out birthdate);

if (!isValidDate)
{
    Console.WriteLine("Invalid date format.");
    return;
}

DateTime currentDate = DateTime.Now;
int age = currentDate.Year - birthdate.Year;

if (birthdate.Date > currentDate.AddYears(-age)) 
    age--;

Console.WriteLine($"Your age is: {age} years!");

Explanation

  1. The program prompts the user to enter their birthdate in a specific format ("yyyy-MM-dd").

  2. It uses DateTime.ParseExact to convert the string input into a DateTime object. This method is chosen to ensure the format is strictly adhered to.

  3. The age is initially calculated by subtracting the birth year from the current year.

  4. 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.

  5. 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