Skip to content

Instantly share code, notes, and snippets.

/AgeAfter10Years
Created Dec 20, 2015

Embed
What would you like to do?
using System;
using System.Globalization; // needed for the DateTime.TryParseExact
class AgeAfterTenYears
{
static void Main()
{
bool notYetBorn = true;
bool invalidDateFormat = true;
while (invalidDateFormat)
{
while (notYetBorn)
{
Console.WriteLine("Please enter a valid birthday (yyyy.mm.dd):");
string birthDay = Console.ReadLine();
DateTime dateTime;
string format = "yyyy.M.d";
if (DateTime.TryParseExact(birthDay, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
//cheking if the format of the input is correct.
{
invalidDateFormat = false; //if format is corect this will end the loop
DateTime today = DateTime.Now;
int age = today.Year - dateTime.Year; //calculating the age
if (dateTime > today.AddYears(-age)) age--; // adjusts the age according to what date is today
if (dateTime.Date <= today.Date) //checkes if the input is a future date
{
Console.WriteLine("You are {0} years old.", age);
Console.WriteLine("After 10 years you will be {0} years old", age + 10);
notYetBorn = false; // this will end the loop
}
else
{
Console.WriteLine("You are NOT yet born."); // if you have added a future date this will be printed
}
}
else
{
Console.WriteLine("Invalid date format."); // if you have added an invalid date it will print this warning.
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.