如何比较两个日期值?

时间:2011-07-14 16:09:06

标签: c# .net datetime

我有一个条目表单,用户每天用当前日期填写表单。现在,我需要显示用户未在表单中输入的日期。

我已检索输入的日期和当月的天数。我不知道如何比较这两个值并打印未输入的日期。

提前致谢。

3 个答案:

答案 0 :(得分:2)

基本上,您需要在该月的第一天开始,并为该月的每一天创建一个DateTime值。将这些天中的每一天与该月的所有输入值进行比较,如果不匹配,则输出生成的DateTime。这是一个启动你的基本算法;您可以根据需要进行修改,以涵盖所需的日期范围:

//I leave you the exercise of actually getting the entered dates in DateTime format
List<DateTime> enteredDates = GetEnteredDatesAsDateTimes();
var unenteredDates = new List<DateTime>();

//I assume you want days for the current month; 
//if not you can set up a DateTime using a specified month/year
var today = DateTime.Today;
var dateToCheck = new DateTime(today.Year, today.Month, 1);

//You could also make sure the date is less than the current date,
//or less than a specified "end date".
while (dateToCheck.Month == today.Month)
{
   //uses Linq, which requires .NET 3.5
   if(!enteredDates.Any(d=>d.Date == dateToCheck.Date))
      unenteredDates.Add(dateToCheck);

   //use the below code instead for .NET 2.0
   //bool inList = false;
   //foreach(var date in enteredDates)
   //   if(enteredDate.Date == date.Date)
   //   {
   //      inList = true;
   //      break;
   //   }
   //if(!inList) unenteredDates.Add(dateToCheck);

   dateToCheck = dateToCheck.AddDays(1);
}

//unenteredDates now has all the dates for which the user didn't fill out the form.

理解这是一个N ^ 2复杂度算法;你将一个列表的每个元素与另一个列表的每个元素进行比较,期望这两个列表具有大致相等的基数。只要你没有检查几个月的日期,它就不应该表现得非常糟糕。您可以通过对输入日期列表进行排序,然后对日期执行二进制搜索而不是线性日期来将其减少为NlogN。这会增加您需要编写的代码,但会减少代码需要采取的步骤。

答案 1 :(得分:0)

如果您有能力跟踪表格填写的日期。所有你需要做的就是用当前月份的长度写一个循环。

此时您需要做的只是一个简单的检查,看看当前的迭代是否存在于您的日期集合中。如果集合中未包含日期,则打印结果。

System.DateTime.DaysInMonth(int year,int month)将确定循环的迭代次数。

您所要做的就是提取当前:月和年。

答案 2 :(得分:0)

我能想到的最简单的方法是打印一年中的所有日期,跳过已在表单中输入的任何日期。例如:

for(int i=1;i<13;i++){
    String month = Integer.toString(i);
    for(int j=1;j<32;j++){
        String date = month+"/"+Integer.toString(j); 
        if (date in listOfValidDates):
            if(date in filedDates):
                continue;
            System.out.println(date)
        }
     }

更新:将示例从伪代码更改为java,因为这是我所知道的与C#最相似的语言。