我想知道如何通过datetimepicker查找两个日期之间的日期数。例如示例日期范围是从2019.02.22到2019.06.19,我必须找到第23个日期(2019.02.23 / 2019.03.23 / 2019.04.23 / 2019.05.23),我希望将结果显示为文本框4,但是通过使用下面的代码尝试并得到结果为3,这是错误的答案。非常感谢任何人都可以帮助我。
DateTime d5 = dateTimePicker1.Value;
DateTime d6 = dateTimePicker3.Value;
int MonthsElapsednew = ((d5.AddDays(1).Year - d6.AddDays(1).Year)
* 12) +(d5.AddDays(1).Month - d6.AddDays(1).Month)
(d5.AddDays(1).Day < d6.AddDays(1).Day ? 1 : 0);
textBox16.Text = MonthsElapsednew.ToString();
答案 0 :(得分:2)
建立在How to get dates between two dates in C#上,就这么简单:
DateTime startdate = new DateTime(2019, 2, 22);
DateTime enddate = new DateTime(2019, 6, 19);
int monthselapsed = Enumerable
.Range(0, int.MaxValue)
.Select(index => new DateTime?(startdate.AddDays(index)))
.TakeWhile(date => date <= enddate)
.Where(day => day.Value.Day == 23)
.Count();