Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

c# - DateTime.AddDays() not working as expected

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.

What is the problem?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


EDIT

There is a little paragraph about it on 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...