按日期范围过滤对象

时间:2018-08-14 12:34:31

标签: c#

我目前正在尝试制定一种算法,将物体的捕获日期(它们是图像)与用户选择的日期范围进行比较。 图像的拍摄日期当前存储为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]);
   }
  }
}

1 个答案:

答案 0 :(得分:3)

将日期存储为日期会更简单,但是如果您没有选择,则应使用以下选项:

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)
{

}

还要注意,有许多if可以做DisplayList.Add(ImageList[i]);的事情很奇怪。
我会尝试将其分解为一个因素:我到底何时需要在该显示列表中添加图像?

然后使用一个if

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