首页 > 解决方案 > 如何在两个日期实例之间查找一个月中给定日期的每月日期

问题描述

我想知道如何通过 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();

标签: c#

解决方案


基于如何在 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();

推荐阅读