WTF: DateTime.AddDays() is not working as expected

by jask2002 1. June 2012 23:36

Working with following code on DateTime AddDays operation I found end result is not the addition of days!!

int increment = 5;
DateTime now = DateTime.Now; //Current Date
now.AddDays(increment); //Increment by 5 days

Console.WriteLine("Today's date:" + DateTime.Now);
Console.WriteLine("New Date:" + now.ToString());

To my surprise it returned New Date without adding 5 days to the Current Date

DateTime

Then I change the printing line to

//Console.WriteLine("New Date:" + now.ToString());//Commented it out
Console.WriteLine("New Date:" + now.AddDays(increment).ToString());

DateTime2

I went back on MSDN for DateTime.AddDays Method

Remarks

“This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation.”

So I change my code for assignment of returned DateTime to the now variable

int increment = 5;
DateTime now = DateTime.Now; //Current Date
now = now.AddDays(increment); //Increment by 5 days
Peace! Smile

PayPal — The safer, easier way to pay online. Has this post helped you? Saved you? If you'd like to show your appreciation. Please buy me a coffee or make a small contribution toward blog's maintenance(to keep it Ads free )

Tags: ,

C# | .Net | DateTime

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About me

Hi there,

My name is  Jas and I'm currently working with Microsoft IIS/ASP.Net Escalation services.  Services

 

Tag cloud

Month List

RecentComments

Comment RSS

TextBox

 

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.