加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 无法在循环中多次添加日期

发布时间:2020-12-15 19:37:53 所属栏目:百科 来源:网络整理
导读:我在选定的索引上有这个代码更改了一个表示月份的下拉列表. DateTime firstDate,lastDate; int mon = DropDownList1.SelectedIndex +1; int year = 2013; GetDates(mon,year,out firstDate,out lastDate); DateTime f = firstDate; DateTime d2 = firstDate.
我在选定的索引上有这个代码更改了一个表示月份的下拉列表.

DateTime firstDate,lastDate;
    int mon = DropDownList1.SelectedIndex +1;
    int year = 2013;

    GetDates(mon,year,out firstDate,out lastDate);
    DateTime f = firstDate;
    DateTime d2 = firstDate.AddDays(7);
    for (;d2.Month  == mon;  )
    {
        d2.AddDays(7);   // value after first iteration is "08-Apr-13 12:00:00 AM"
                        // but beyond first iteration the value remains the same.
    }


    private void GetDates(int mon,int year,out DateTime firstDate,out DateTime lastDate)
    {       
        int noOfdays = DateTime.DaysInMonth(year,mon);
        firstDate = new DateTime(year,mon,1);
        lastDate = new DateTime(year,noOfdays);
    }

我希望d2会在每次迭代中持续增加7天,只要结果值在同一个月内.但似乎价值只增加一次.即从01日至4月13日上午12:00:00至08日 – 4月13日上午12:00:00

解决方法

您必须将更改的日期对象分配回日期对象d2,因为DateTime对象是不可变的. AddDays方法返回新对象而不是更改调用它的对象,因此您必须将其分配回调用对象.

d2 = d2.AddDays(7);

编辑为什么它适用于第一次迭代?

因为您通过在循环前7天添加来初始化日期对象.

DateTime d2 = firstDate.AddDays(7);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读