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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15359887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:30:26  来源:igfitidea点击:

Datetime in C# add days

c#datec#-4.0datetimeadd

提问by Nomi Ali

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?

但是这段代码不起作用,天数不加!我在做什么愚蠢的错误?

采纳答案by Darren Young

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

回答by Jensen

You need to catch the return value.

您需要捕获返回值。

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

DateTime.AddDays方法返回一个对象是谁的值是实例的日期和时间,增加值的总和。

endDate = endDate.AddDays(addedDays);

回答by Freeman

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

这是因为该AddDays()方法返回一个 new DateTime,您没有在任何地方分配或使用它。

Example of use:

使用示例:

DateTime newDate = endDate.AddDays(2);

回答by bash.d

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

你为什么使用Int64AddDays要求double添加一个-value。然后你需要使用AddDays.See here的返回值。

回答by coder

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

将结束日期分配给某个日期变量,因为AddDays方法返回新的日期时间作为结果..

Datetime somedate=endDate.AddDays(2);

回答by The Martian

Use this:

用这个:

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

回答by Nayas Subramanian

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