C# DateTime.AddDays() 未按预期工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11583601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:27:42  来源:igfitidea点击:

DateTime.AddDays() not working as expected

c#visual-studio-2010datetime

提问by Sas Gabriel

I have this simple program:

我有这个简单的程序:

        DateTime aux = new DateTime(2012, 6, 12, 12, 24, 0);
        DateTime aux2 = new DateTime(2012, 6, 12, 13, 24, 0);
        aux2.AddDays(1);

       Console.WriteLine((aux2 - aux).TotalHours.ToString());

        Console.ReadLine();

I debugged this and found aux2.AddDays(1);doesn't seem to work, what am I missing here? it should return 25 but the answer is one.

我调试了这个,发现aux2.AddDays(1);似乎不起作用,我在这里错过了什么?它应该返回 25 但答案是 1。

What is the problem?

问题是什么?

also AddHoursdoesn't work, I guess that the others aren't working too.

AddHours不起作用,我想其他人也不起作用。

采纳答案by Jodrell

It does work but you don't do anything with the return value, try

它确实有效,但您对返回值没有做任何事情,请尝试

aux2 = aux2.AddDays(1);

DateTimes share this facet of immutability with Strings.

DateTimes 与 s 共享不变性的这一方面String



EDIT

编辑

There is a little paragraph about it on MSDN

MSDN上有一段关于它的内容

This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation.

此方法不会更改此 DateTime 的值。相反,它返回一个新的 DateTime,其值是此操作的结果。

回答by Zbigniew

DateTime.AddDaysreturns new DateTime that adds specified number of days. You need to assign it to your variable:

DateTime.AddDays返回添加指定天数的新日期时间。您需要将其分配给您的变量:

aux2 = aux2.AddDays(1);

回答by Neil Meyer

You are working with immutable functions.

您正在使用不可变函数。

The DateTime function is immutable, once you set variable equal to it, it cannot change, you can though set new variables equal to a working of the function. The AddDay function takes the variable you put into it, but it does not change the original variable, that remains immutable. So you need to set a new variable equall to the original variable + a day.

DateTime 函数是不可变的,一旦您将变量设置为等于它,它就无法更改,但您可以将新变量设置为等于该函数的工作。AddDay 函数接受您放入其中的变量,但它不会更改原始变量,该变量保持不变。因此,您需要将新变量设置为等于原始变量 + 一天。

So all you really need to do is change

所以你真正需要做的就是改变

aux2.AddDays(1);

aux2.AddDays(1);

to

aux2 = aux2.Adddays(1);

aux2 = aux2.Adddays(1);

and then the rest of your comparison functions should work

然后其余的比较函数应该可以工作