Search code examples
c#timerstopwatch

Shows timer (minutes and seconds) in console


I need shows the timer running in console. I use stopwatch:

System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

public void startTime()
{
    stopwatch.Start();
}

public void GetTime(){
    stopwatch.Stop();
    TimeSpan timeSpan = stopwatch.Elapsed;
    var timeElapsed = (string.Format("\nTime Elapsed: {0} minute(s) {1} second(s)",
    timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10 + "\n")).ToString();
}

I need shows in console the timer running normally: 00:00:01, 00:00:02, 00:00:03 ... etc

How can I do this?


Solution

  • something like this?

    Stopwatch sw = new Stopwatch();
    sw.Start();
    
    while (true)
    {
        Console.SetCursorPosition(0, 0);
        Console.Write(sw.Elapsed.ToString("g"));
    
        if (sw.Elapsed.TotalMinutes > 30)
            break;
    }