C#如果它们在日期之间,则添加项目

1 c# date

我创建了一个程序,如果项目介于日期之间,则需要添加项目,这是我使用的代码:

if (day >= fromDay - 1 && day <= tillDay && month >= fromMonth - 1 && month <= tillMonth && year >= fromYear - 1 && year <= tillYear) { listBox1.Items.Add(OpenFiles[m_index].getFileName()); }

代码工作正常,但它有一个错误:它检查日,月和年是否在开始和结束之间.所以即使你想在2011年2月19日至2011年4月15日期间添加一些东西,它也不会添加或看到任何东西.请帮我解决一下这个.

Jon*_*eet 5

您应该比较日期而不是日期的组成部分:

// Presumably you can determine these once... (possibly rename to earliestValid
// and latestValid, or something like that?)
DateTime from = new DateTime(fromYear, fromMonth, fromDay);
DateTime to = new DateTime(toYear, toMonth, toDay);

// Then for each candidate...
...
DateTime date = new Date(year, month, day);
if (date >= from && date <= to)
{
    listBox1.Items.Add(...);
}
Run Code Online (Sandbox Code Playgroud)

(当然,对于日期类型而不是日期和时间,请看看Noda Time :)

  • 哦,天啊,乔恩醒了 - 我们"地球人"可以去睡觉了; ;-) (2认同)