Search code examples
c#loopsleap-year

relevant loop and leap year c#


I am going to say in advance, that I am a beginner in programming and this question might seem quite irrelevant. However, I truly wonder how to proceed in this situation.

This is my code:

string startdate;

Console.WriteLine("Please, type in your birthdate (dd-mm-yyyy)");
startdate = Console.ReadLine();
DateTime bday = DateTime.Parse(startdate);
        // prob 1.
DateTime now = DateTime.Now;
TimeSpan ts1 = now.Subtract(bday);
DateTime dt = new DateTime(0001, 01, 01);
TimeSpan ts2 = new TimeSpan(365, 0, 0, 0);
        //prob2.
TimeSpan ts3 = new TimeSpan(3650, 0, 0, 0);
dt = dt + ts1 - ts2;
Console.WriteLine("Your current age is:{0}", dt.ToString("yy"));
dt = dt + ts3;
Console.WriteLine("Your Age after 10 years will be:{0}", dt.ToString("yy"));

Problem 1: I would like to create a loop where if the info that is given in the console is different from dd-mm-yyyy, to repeat the whole process again.

Problem 2: I would like to see whether the next year(from the current one) is a leap year, and thus know whether ts2 should be 365 days or 366.

Thank you in advance.


Solution

  • The Leap year problem is not really a problem thanks to the Framewrok

    int daysToAdd = 0;
    for(int i = 1; i <= 10; i++)
       daysToAdd += (DateTime.IsLeapYear(DateTime.Today.Year + i) ? 366 : 365);
    

    The first problem could be solved with

    DateTime inputDate;
    while(true)
    {
        Console.WriteLine("Please, type in your birthdate (dd-mm-yyyy)");
        string startdate = Console.ReadLine();
        if(DateTime.TryParseExact(startdate, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out inputDate))
            break;
    }