AcedPI
AcedPI

Reputation: 11

How to automatically add a day every 24 hours in DateTime

I'm writing a code where I can advance the current time by pressing Enter. I've managed to get that going, but I need the date to advance as well every 24 hours. Here's my code:

var time = new DateTime(2025, 4, 15, 12, 00, 0);

string currentDate = time.ToString("dd/MM/yyyy");
string currentTime = time.ToString("HH:mm");
int timeAdd = 4;

Console.WriteLine("Press 'Enter' to advance...");
ConsoleKeyInfo userInput = Console.ReadKey();

if (userInput.Key == ConsoleKey.Enter) {
currentTime = time.AddHours(timeAdd).ToString("HH:mm");
timeAdd = timeAdd + 4;

This is working fine, but at 00:00 everyday (or if I advance the time at for example 22:00 for 3 hours then at 01:00) the day value should also increase by one. At the end of every month the month should increase too, and then the year.

An optional question to answer is; Is there a better way to advance the time? As you see, right now I'm advancing the time by first 4, then 8, then 12 and so on, hours. That's because as I can't set the time to anything after it's declared, i have to add 4 additional hours each time.

Edit: This isn't the full code and it's in a while loop, I've decided to include only the necessary parts for the question.

Upvotes: 0

Views: 214

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

Your problem is that DateTime is an immutable structure. Every method that should modify it returns a new instance, and you are throwing it away.
Use this instead:

var time = new DateTime(2025, 4, 15, 12, 00, 0);

string currentDate = time.ToString("dd/MM/yyyy");
string currentTime = time.ToString("HH:mm");
int timeAdd = 4;

Console.WriteLine("Press 'Enter' to advance...");
ConsoleKeyInfo userInput = Console.ReadKey();

if (userInput.Key == ConsoleKey.Enter) 
{
    time = time.AddHours(timeAdd);
    currentDate = time.ToString("dd/MM/yyyy"); // refresh date
    currentTime = time.ToString("HH:mm"); // refresh time
}

Upvotes: 4

Related Questions