C # 中的日期时间加上天数

我想在一些日期中加上天数,我有一个这样的代码:

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

但是这个代码不工作,天没有添加! 我在做什么愚蠢的错误?

254473 次浏览

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);

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);

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.

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);

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

Datetime somedate=endDate.AddDays(2);

Use this:

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

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);