Date and time continuous C# Exercise - C# Programming Course

 Exercise

Date and time continuous

 Objetive

Create a program that shows the current time in the top-right corner of the screen with the format:

12:52:03

The program should pause for one second and then display the time again in the same location.

 Example Code

// Import the necessary namespaces for working with date, time, and console operations
using System;

class Program
{
    // Main method where the program execution starts
    static void Main()
    {
        // Infinite loop to continuously display the time
        while (true)
        {
            // Get the current time
            string currentTime = DateTime.Now.ToString("HH:mm:ss");  // Formats the current time as HH:mm:ss (24-hour format)

            // Move the cursor to the top-right corner of the console window
            Console.SetCursorPosition(Console.WindowWidth - currentTime.Length - 1, 0); // Position at top-right corner

            // Display the current time at the cursor position
            Console.Write(currentTime);  // Writes the current time to the console at the specified location

            // Pause for 1 second before updating the time again
            System.Threading.Thread.Sleep(1000);  // Pauses the program for 1000 milliseconds (1 second)

            // Clear the previous time by moving the cursor back to the top-right corner and overwriting it
            Console.SetCursorPosition(Console.WindowWidth - currentTime.Length - 1, 0);  // Move to the same position
            Console.Write("       ");  // Clear the previous time by overwriting it with blank spaces
        }
    }
}

Juan A. Ripoll - Programming Tutorials and Courses © 2025 All rights reserved.  Legal Conditions.