C# 如何在DateTime中每24小时自动添加一天

C# 如何在DateTime中每24小时自动添加一天,c#,C#,我正在编写一个代码,通过按Enter键可以提前当前时间。我已经设法做到了,但我也需要每24小时提前一次约会。这是我的密码: 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键可以提前当前时间。我已经设法做到了,但我也需要每24小时提前一次约会。这是我的密码:

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;
这可以正常工作,但每天00:00(或者如果我将时间提前3小时,例如22:00,则在01:00),日值也应增加1。在每个月底,月份也应该增加,然后是一年

要回答的可选问题是:;有没有更好的方法来推进时间?如你所见,现在我把时间提前了4小时,然后是8小时,然后是12小时,依此类推。这是因为在声明时间之后,我无法将时间设置为任何时间,因此每次我必须增加4个小时


编辑:这不是完整的代码,它在一个while循环中,我决定只包含问题的必要部分。

您的问题是
DateTime
是一个不可变的结构。每一个应该修改它的方法都会返回一个新实例,而您正在丢弃它。
改用这个:

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
}

您的问题是
DateTime
是一个不可变的结构。每一个应该修改它的方法都会返回一个新实例,而您正在丢弃它。
改用这个:

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
}

“我不能在声明后设置时间”-为什么?如果您想更新日期,只需重新分配
currentDate
,就像您在代码段开头所做的那样。然后,我需要检查一天是否已经过去,我的问题就是这个。另外,我的意思是我不能在声明DateTime方法后更改它。所以如果我只做了
currentTime=time.AddHours(4).ToString(“HH:mm”)它会一次又一次地先输出12:00,然后输出16:00,然后输出16:00。“我不能在声明后设置时间”-为什么?如果您想更新日期,只需重新分配
currentDate
,就像您在代码段开头所做的那样。然后,我需要检查一天是否已经过去,我的问题就是这个。另外,我的意思是我不能在声明DateTime方法后更改它。所以如果我只做了
currentTime=time.AddHours(4).ToString(“HH:mm”)它会反复输出12:00、16:00和16:00。谢谢你的回答,它完美地回答了我的可选问题。虽然我的主要问题仍然存在,但我不知道你的意思<代码>添加小时数
自动添加天数。再次设置
currentDate=time.ToString(“dd/MM/yyyyy”)
应该会向您显示这一点,非常感谢。这解决了我的主要问题。为了方便起见,我建议你在帖子中加入这条评论,我将把它标记为答案。再次感谢。谢谢你的回答,它完美地回答了我的可选问题。虽然我的主要问题仍然存在,但我不知道你的意思<代码>添加小时数
自动添加天数。再次设置
currentDate=time.ToString(“dd/MM/yyyyy”)
应该会向您显示这一点,非常感谢。这解决了我的主要问题。为了方便起见,我建议你在帖子中加入这条评论,我将把它标记为答案。再次感谢你。