【问题标题】:Filtering Objects by a date range按日期范围过滤对象
【发布时间】:2018-08-14 21:51:46
【问题描述】:

目前,我正在尝试创建一种算法,将对象的捕获日期(它们是图像)与用户选择的日期范围进行比较。 图像的拍摄日期当前存储为 mm/yyyy。

我将捕获的年份和月份转换为整数,然后将它们拆分并存储 startMonth 和 startYear 是用户输入的值。

我将捕获日期的年份和月份转换为整数,在它们被拆分并存储为monthyear.startMonthstartYear 存储用户输入的值之后。

如果它在日期范围内,那么我将它从存储的列表中添加到“DisplayList”中。

我需要它来识别开始月份可以大于结束月份的日期。我可能错过了一些简单的东西。

string month = split[0];
string year = split[1];

if (startYear <= Convert.ToInt32(year) && endYear >= Convert.ToInt32(year))
{
  if (startYear == Convert.ToInt32(year) && endYear == Convert.ToInt32(year))
  {
    if (startMonth <= Convert.ToInt32(month) && endMonth >= Convert.ToInt32(month))
    {
      DisplayList.Add(ImageList[i]);     // Adds it to the DisplayList                          
    }
  }
  else if (startYear == Convert.ToInt32(year) || endYear == Convert.ToInt32(year))
  {
   if (startMonth <= Convert.ToInt32(month) && endMonth >= Convert.ToInt32(month))
   {
     DisplayList.Add(ImageList[i]);
   }
   else if (startYear == Convert.ToInt32(year) && startMonth <= Convert.ToInt32(month))
   {
     DisplayList.Add(ImageList[i]);
   }
   else if (endYear == Convert.ToInt32(year) && startMonth >= Convert.ToInt32(month))
   {
     DisplayList.Add(ImageList[i]);
   }
  }
}

【问题讨论】:

  • 为什么不使用monthyear 创建两个DateTime 对象并比较这些日期? (new DateTime(year, month, 1);)
  • 为什么不只使用一个整数呢? "yyyymm" ,例如 Dec 2018 => 201812 那么你可以简单地使用 "" ...(当然是 DateTime)
  • 您是在比较没有天数的日期吗?如果是,那么我认为只有几个条件可以让它发挥作用。
  • 您通过将日期存储在该模式中使这变得复杂。您应该简单地使用日期时间,然后简单地查询它。
  • 将日期存储为日期比转换代码更容易比较

标签: c#


【解决方案1】:

将您的日期存储为日期会更简单,但如果您别无选择,则应使用以下方法:

var startDate = new DateTime(Convert.ToInt32(startYear), Convert.ToInt32(startMonth), 1);
var endDate = new DateTime(Convert.ToInt32(endYear), Convert.ToInt32(endMonth), 1);
var date = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);

// do whatever comparisons with date, startDate and endDate
if(startDate <= date && date <= endDate)
{

}

还要注意,有很多ifs 来做DisplayList.Add(ImageList[i]); 是很奇怪的。
我会尝试考虑它:我什么时候需要将图像添加到该显示列表?

然后使用一个if

if(thatCondition ||
   thisCondition ||
   thatOtherCondition)
{
    DisplayList.Add(ImageList[i]);
}

【讨论】:

  • @DanScott 我发现我的解决方案更清晰,只是试图判断你的解决方案是否正确(试图找到边缘情况或任何会破坏它的东西)让我头疼。无论如何,我的观点不是关于比较,而是关于以更简单的方式进行比较的转换。在发表评论之前,您在此页面上停留了多长时间?我在 1 小时前编辑了这个答案^^
猜你喜欢
  • 2014-09-04
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 2021-05-25
  • 2018-06-19
  • 1970-01-01
相关资源
最近更新 更多