C# Exercise: 218 Date and time continuous

In this exercise, you need to create a program that displays the current time in the top-right corner of the screen with the format "HH:mm:ss". The program should pause for one second and then display the time again in the same location. This exercise will allow you to practice working with dates and times in C#, as well as controlling the output position on the console.

The main goal is to continuously update the time and display it in real-time. You will learn how to use DateTime.Now to get the current time and how to control the output location on the console using Console.SetCursorPosition() to ensure the time is printed in the top-right corner.

This exercise is useful for understanding real-time interface updates in console applications.



 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
        }
    }
}