【问题标题】:Filter or Check Date in A Date Range过滤或检查日期范围内的日期
【发布时间】:2018-08-19 10:57:32
【问题描述】:

这完全是一个简单或基本的要求。我正在尝试使用C# 从日期列表中获取日期。所以我所做的,创建了一个函数并使用for 循环对其进行迭代。我尝试将列表函数分为两个范围,并从DatePicker 控件传递值,如下所示:

private void btnClick_Click(object sender, EventArgs e)
{
    DateTime theFromDate = dateTimePicker1.Value;
    DateTime theToDate = dateTimePicker2.Value;

    List<DateRange> lstRange = GetDateRange();

    /**Trying To Get The Date From The Range - Starts**/
    var dates = new List<DateTime>();

    for (var dt = theFromDate; dt <= theToDate; dt = dt.AddDays(1))
    {
        dates.Add(dt);
        //MessageBox.Show(dt.Date.ToString());
    }

    List<DateRange> lst = GetDateRange();
    foreach(var item in lst)
    {
        if(theFromDate <= item.EndtDate.Date)
        {
            MessageBox.Show(theFromDate.ToString("dd-MMM-yyyy") + " in the date range!");
        }
        else
        {
            MessageBox.Show(theFromDate.ToString("dd-MMM-yyyy") + " not in the date range!");
        }
    }
    /**Trying To Get The Date From The Range - Ends**/
}
public class DateRange
{
    public DateTime date { set; get; }
    public DateTime EndtDate { set; get; }
}

/**List of Dates Here - Starts**/
public List<DateRange> GetDateRange()
{
    List<DateRange> lstDate = new List<DateRange>();

    DateRange aDateRange = new DateRange();
    aDateRange.StartDate = Convert.ToDateTime("10-Aug-2018");
    aDateRange.EndtDate = Convert.ToDateTime("13-Aug-2018");
    lstDate.Add(aDateRange);

    return lstDate;
}
/**List of Dates Here - Ends**/

不幸的是,尽管列表具有特定日期,但它不会返回所需的输出。

更新 1: 预期输出 - FromDateToDate 值存储在列表中。

 FromDate      ToDate 
 10-AUG-2018   13-AUG-2018

 **in the date range**

 FromDate      ToDate 
 13-AUG-2018   16-AUG-2018

 **in the date range** //As 13 is the end date in the given list

 FromDate      ToDate 
 8-AUG-2018    10-AUG-2018

 **in the date range** //As 10 is the start date in the given list

 FromDate      ToDate 
 8-AUG-2018    8-AUG-2018

 **not in the date range** //As 10 is the start date in the given list

【问题讨论】:

  • 您的代码令人困惑。尝试解释您想要实现的目标,添加示例输入和相应的期望输出。覆盖aDateRange.date 三遍的目的是什么,并且在将最后一个添加到列表之前使用常量?您的 GetDateRange 将返回 DateRange 的单个实例的相同列表。
  • 请查看更新后的帖子@ZorgoZ。

标签: c# .net winforms for-loop


【解决方案1】:

老实说,我很难弄清楚你想要做什么,而且我不禁觉得你“过度设计”了你的解决方案。

首先,“日期范围”只是两个日期 - 一个起始日期和一个结束日期,但您的 GetDateRange 方法里面有 4 个日期,它以列表的形式返回。这令人难以置信的混乱-我不确定您是要从中获取多个日期范围(多对)还是单个日期范围。 鉴于所有日期都是一个接一个,我将假设是后者。

public class DateRange
{
  public DateTime StartDate { get; set; }
  public DateTime EndDate { get; set; }
}

public DateRange GetStaticDateRange()
{
  //It seems counterproductive to add all 4 dates here, 
  //given that these are all one after the other
  return new DateRange
  { 
    StartDate = new DateTime(2018, 7, 10),
    EndDate = new DateTime(2018, 7, 13) 
  };
  //Obviously this can be modified as needed to return whatever combination of 
  //start-end dates you want, but this method will only ever return ONE range
  //However, this method could just as well accept parameters and / or access other resources
}

public bool IsInDateRange(DateTime dateToCheck, DateRange targetRange)
{
  //An argument can be made to use non-encompassing comparisons for both checks
  //depending on your requirements
  return dateToCheck >= targetRange.StartDate && dateToCheck <= targetRange.EndDate;
}

上面有一个简单的类用于存储“日期范围”(恰当地称为DateRange),以及一个示例方法,用于检查给定的DateTime 在特定的DateRange 中是否有效。

编辑:
好的,所以从您更新的问题来看,您似乎正在尝试查找两个日期范围是否重叠(完全)。

在这种情况下,下面的代码应该会有所帮助。

public static bool DateRangesOverlap(DateRange range1, DateRange range2)
{
  return (range1.StartDate >= range2.StartDate && range1.StartDate <= range2.EndDate) || 
         (range1.EndDate >= range2.StartDate && range1.EndDate <= range2.EndDate);
}

这是.NET Fiddle 上的一个工作示例,其中包含您的测试用例。请注意,为了简洁起见,我仍在使用上面定义的 DateRange 类,并添加了一个构造函数。

另外请注意,DateRange 类没有对 start 和 end 参数进行完整性检查,并且可以创建一个 DateRange 将两个值颠倒(即 start > end),这显然会导致错误。但这只是一个例子,所以我把这些东西的实现留给你。 ;)

【讨论】:

  • 感谢您的回答,如果您有时间,请查看更新后的帖子@Shaamaan。
【解决方案2】:

您的代码中有一些错误。 例如,在 GetDateRange() 中,您只向该范围添加一个日期,其日期将设置为 2018 年 8 月 13 日,所以这是您需要修复的一件事,如果您的目标是在日期范围,可以使用 Linq。要比较范围,我还建议使用 DateTime.CompareTo 方法。请参阅下面的代码以更正您的错误:

    public static bool RangeContainsDate(DateTime queriedDateTime)
        {
            var queriedDateRange = new DateRange { Date = queriedDateTime };
            List<DateRange> dates = GetDateRange();
            return dates.Where(d => d.CompareTo(queriedDateRange) == 0).Any();
        }

        /**List of Dates Here - Starts**/
        public static List<DateRange> GetDateRange()
        {
            List<DateRange> lstDate = new List<DateRange>();

            DateRange aDateRange1 = new DateRange();
            aDateRange1.Date = Convert.ToDateTime("10-Aug-2018");
            lstDate.Add(aDateRange1);

            DateRange aDateRange2 = new DateRange();
            aDateRange2.Date = Convert.ToDateTime("11-Aug-2018");
            lstDate.Add(aDateRange2);

            DateRange aDateRange3 = new DateRange();
            aDateRange3.Date = Convert.ToDateTime("12-Aug-2018");
            lstDate.Add(aDateRange3);

            DateRange aDateRange4 = new DateRange();
            aDateRange4.Date = Convert.ToDateTime("13-Aug-2018");
            lstDate.Add(aDateRange4);

            return lstDate;
        }
    }
}

public class DateRange : IComparable<DateRange>
{
    public DateTime Date { set; get; }

    public int CompareTo(DateRange other)
    {
        if (ReferenceEquals(other, null))
        {
            return -1;
        }
        return DateTime.Compare(Date, other.Date);
    }

}

【讨论】:

  • 感谢您的回答,如果您有时间,请查看更新后的帖子@PiJei。
【解决方案3】:
    private void btnClick_Click(object sender, EventArgs e)
    {
        //DateTime theFromDate = dateTimePicker1.Value;
        DateTime theToDate = dateTimePicker2.Value;

        List<DateRange> lstRange1 = GetDateRange();
        List<DateRange> lstRange2 = GetDateRange();

        var result = lstRange1.Any(x => x.date >= theToDate && lstRange2.Any(y => y.date < theToDate));

        if (result)
        {
            MessageBox.Show(theToDate.ToString("dd-MMM-yyyy") + " in the date range!");
        }
        else
        {
            MessageBox.Show(theToDate.ToString("dd-MMM-yyyy") + " not in the date range!");
        }
    }



    public List<DateRange> GetDateRange()
    {
        List<DateRange> lstDate = new List<DateRange>();

        lstDate.Add(new DateRange { date = Convert.ToDateTime("10-Aug-2018") });
        lstDate.Add(new DateRange { date = Convert.ToDateTime("11-Aug-2018") });
        lstDate.Add(new DateRange { date = Convert.ToDateTime("12-Aug-2018") });
        lstDate.Add(new DateRange { date = Convert.ToDateTime("13-Aug-2018") });

        return lstDate;
    }

【讨论】:

  • 感谢您的回答,如果您有时间,请查看更新后的帖子@Valeh Mikayilzadeh。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 2015-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多