2017-08-04 114 views
3

我有一个for循环日期时间如何counter不增加。我没有看到原因。你能帮我吗?日期时间在For循环

private void ubGO_Click(object sender, EventArgs e) 
{ 
    DateTime startDate = udteMin.DateTime.Date; 
    DateTime endDate = udteMax.DateTime.Date; 

    for (DateTime counter = startDate; counter <= endDate; counter.AddDays(1)) 
    { 
     MessageBox.Show(counter.Date.ToString() + "   " + counter.AddDays(1).Date.ToString()); 
    } 
} 

回答

6

AddDays返回一个新的DateTime对象。它不会改变你现有的一个。你需要重新分配计数器的结果AddDays

counter = counter.AddDays(1); 
+0

不应该在IDE中有这样的警告? – hoodaticus

+1

是啊取决于你的IDE和设置,你可以得到一个警告,你扔掉了方法调用的结果 –