Datetime in C# add days

2019-01-13 23:57发布

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?

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-14 00:34

you can add days to 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);
查看更多
祖国的老花朵
3楼-- · 2019-01-14 00:36

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

Datetime somedate=endDate.AddDays(2);
查看更多
Ridiculous、
4楼-- · 2019-01-14 00:43

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);
查看更多
Explosion°爆炸
5楼-- · 2019-01-14 00:43

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.

查看更多
Juvenile、少年°
6楼-- · 2019-01-14 00:49

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);
查看更多
ら.Afraid
7楼-- · 2019-01-14 00:50

Use This:

     DateTime dateTime = new DateTime();
     dateTime = DateTime.Now;
     DateTime newDateTime = new DateTime();
    TimeSpan NumberOfDays = new TimeSpan(2, 0, 0, 0, 0);
    newDateTime = dateTime.Add(NumberOfDays);
查看更多
登录 后发表回答