Datetime in C# add days

C#DateC# 4.0DatetimeAdd

C# Problem Overview


I want to add days in some date. I have a code like this:

DateTime endDate = Convert.ToDateTime(this.txtStartDate.Text); 
Int64 addedDays = Convert.ToInt64(txtDaysSupp.Text); 
endDate.AddDays(addedDays); 
DateTime end = endDate; 
this.txtEndDate.Text = end.ToShortDateString();

But this code is not working, days are not added! What the stupid mistake I'm doing?

C# Solutions


Solution 1 - C#

DateTime is immutable. That means you cannot change it's state and have to assign the result of an operation to a variable.

endDate = endDate.AddDays(addedDays);

Solution 2 - C#

You need to catch the return value.

The DateTime.AddDays method returns an object who's value is the sum of the date and time of the instance and the added value.

endDate = endDate.AddDays(addedDays);

Solution 3 - C#

Its because the AddDays() method returns a new DateTime, that you are not assigning or using anywhere.

Example of use:

DateTime newDate = endDate.AddDays(2);

Solution 4 - C#

You can add days to a date like this:

// add days to current **DateTime**
var addedDateTime = DateTime.Now.AddDays(10);

// add days to current **Date**
var addedDate = DateTime.Now.Date.AddDays(10);

// add days to any DateTime variable
var addedDateTime = anyDate.AddDay(10);

Solution 5 - C#

Assign the enddate to some date variable because AddDays method returns new Datetime as the result..

Datetime somedate=endDate.AddDays(2);

Solution 6 - C#

Use this:

DateTime dateTime =  DateTime.Now;
DateTime? newDateTime = null;
TimeSpan numberOfDays = new TimeSpan(2, 0, 0, 0, 0);
newDateTime = dateTime.Add(numberOfDays);

Solution 7 - C#

Why do you use Int64? AddDays demands a double-value to be added. Then you'll need to use the return-value of AddDays. See here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNomi AliView Question on Stackoverflow
Solution 1 - C#SteveView Answer on Stackoverflow
Solution 2 - C#JensenView Answer on Stackoverflow
Solution 3 - C#FreemanView Answer on Stackoverflow
Solution 4 - C#Nayas SubramanianView Answer on Stackoverflow
Solution 5 - C#coderView Answer on Stackoverflow
Solution 6 - C#user8537597View Answer on Stackoverflow
Solution 7 - C#bash.dView Answer on Stackoverflow