Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.AddDays() not working as expected

Tags:

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.

like image 550
Sas Gabriel Avatar asked Jul 20 '12 16:07

Sas Gabriel


2 Answers

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.

like image 92
Jodrell Avatar answered Sep 19 '22 06:09

Jodrell


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

aux2 = aux2.AddDays(1); 
like image 32
Zbigniew Avatar answered Sep 21 '22 06:09

Zbigniew