Home > Back-end >  How to store a specific date-time through a console.readline statement?
How to store a specific date-time through a console.readline statement?

Time:12-01

I have tried to write multiple programs relating to date/time (including Random.Next()), but I have a persisting problem. Every time I use a Console.ReadLine() statement (or some other statement that would cause the code to pause and resume) it refreshes the variable set by date/time as well as every variable caused by or modified by date/time in any way. Is there a way to store the time the program is run instead of the current time? (I'm using an online editor, dotnetfiddle.net, if that changes anything)

Here's a few examples:

using System;

namespace timeTest
{
    public class Program
    {
        public static void Main()
        {
            Random random = new Random();//Random is based off of time, which updates
            Console.WriteLine("Randomizer: "   random.Next(1,11));//Prints random number
            
            long time = DateTime.Now.Ticks;
            Console.WriteLine("Time in ticks: " time);//Prints time in ticks
            
            int hr = DateTime.Now.Hour;
            int min = DateTime.Now.Minute;
            int sec = DateTime.Now.Second;
            Console.WriteLine("Military time: " hr ":" min ":" sec);//Prints time on the clock
            
            int sec2 = sec*2;//Stores value in a different variable times two
            Console.WriteLine("2x the current second: " sec2);//Prints twice the second
            
            while (true) {Console.ReadLine();}//Every time Console.ReadLine is called, it changes again
        }
    }
}

CodePudding user response:

DateTime.Now is a calculated property. It returns the current time at the exact moment it is called. When you run under the debugger, it always gets the value it has at the moment the value is evaluated by the debugger. Your program won't notice that, but it is something you need to keep in mind.

However, you have a conceptual error here:

int hr = DateTime.Now.Hour;
int min = DateTime.Now.Minute;
int sec = DateTime.Now.Second;

Because DateTime.Now is evaluated each time it is called, this returns a new instance of the time with every call. This may result in the minute not matching the hour displayed (when the hour just changes between the first and the second line, your displayed time will be an hour off).

Evaluate the value once:

DateTime now = DateTime.Now;
int hr = now.Hour;
int min = now.Minute;
int sec = now.Second;

You'll note that in this case, the value of now won't change, even if you stop in the debugger.

Note that there are also standard-formatting options that don't require you to separate the values yourself, just do

Console.WriteLine($"{now:T}"); // standard (localized) time format
  • Related