DateTime.Add() query

  • Thread starter Thread starter madhur
  • Start date Start date
M

madhur

Hello

If I create a DateTime instance like this :
DateTime d=DateTime.Now();
And then
d.AddDays(3);

The 3 days doesnt get added to it. But If I do like this :

DateTime d=DateTime.Now.AddDays(4);

The days gets added correctly.

Can anyone explain me the behaviour ??

Madhur
 
madhur said:
Hello

If I create a DateTime instance like this :
DateTime d=DateTime.Now();
And then
d.AddDays(3);

The 3 days doesnt get added to it. But If I do like this :

DateTime d=DateTime.Now.AddDays(4);

The days gets added correctly.

Can anyone explain me the behaviour ??

..AddDays is a _function_ that returns the _new_ value, not a method
that changes the existing value. Thus when you do

d.AddDays(3);

you are saying: Take the value of d, add three days to it, then do
nothing with the result. The three days does get added to it; but the
result is then thrown away.

But when you say

d=DateTime.Now.AddDays(4);

you are saying: Take the value of DateTime.Now, add four days to it,
and _assign the resulting value to d_.

If you want to change d from its current value to (its current value
plus three days), you should say

d = d.AddDays(3);
 
Hi Madhur,

You have added 3 days to d, but you did not store the value to any variable.
So as intialized in the first step d has the present time alone.
Moreover you have used DateTime.Now(), Now is the property but it is used
like a method.

This might work correctly.
DateTime d = DateTime.Now;

d=d.AddDays(3);

Regards,

Valli.

www.syncfusion.com
 
madhur said:
If I create a DateTime instance like this :
DateTime d=DateTime.Now();
And then
d.AddDays(3);

The 3 days doesnt get added to it. But If I do like this :

DateTime d=DateTime.Now.AddDays(4);

The days gets added correctly.

Can anyone explain me the behaviour ??

Whenever something surprising happens, it's best to consult the
documentation. Here's part of what MSDN says about DateTime.AddDays in
the "Remarks" section:

<quote>
This method does not change the value of this DateTime. Instead, a new
DateTime is returned whose value is the result of this operation.
</quote>
 
Jon said:
Whenever something surprising happens, it's best to consult the
documentation. Here's part of what MSDN says about DateTime.AddDays in
the "Remarks" section:

<quote>
This method does not change the value of this DateTime. Instead, a new
DateTime is returned whose value is the result of this operation.
</quote>

Thanks to all those who replied. Indeed I should have consulted the
documentation first.
 
Back
Top