Search code examples
c#loopsdatetimeconsole-applicationconditional-statements

Looping within a timespan


Writing a simple console application to learn a few things. The application uses a for loop and and behaves as expected, except when it reaches the while loop with start and end DateTime conditions. However the while loop just keep printing out "Graduation" for all eternity..

I simply want the while loop to run and print out "graduation" to the console for 5 seconds, then continue counting up to 2020. What am I missing?

static void Main(string[] args)
{

    DateTime start = DateTime.Now.AddSeconds(0);

    DateTime end = DateTime.Now.AddSeconds(5);
    

    for (int i = 1988; i < 2020; i += 2)
    {


        if (i == 2000)
        {
            Console.WriteLine("New Mellenium");

            continue;
        }



        if (i == 2006)
        {
           
           
            Console.WriteLine("Age of maturity");

            continue;
        }


        if (i == 2014)
        {

            while (start < end)
            {

                Console.WriteLine("Graduation!!!");

                continue;
            }

            
        }

        

        Console.WriteLine(i);
        Console.ReadKey();
    
    
    
    }

Thanks


Solution

  • As my first comment, you never change the start and end dateTime objects, that's the reason!

    In this case, you could try checking if the end has hitted by current time.

    while (DateTime.Now < end)
       Console.WriteLine("Graduation!!!");