# P5: Calculate Age

#### Age Calculator Program

```csharp
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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://raviram.gitbook.io/c-programing/problem-based-learning/p5-calculate-age.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
