c#添加在日期之间的项

本文关键字:之间 日期 添加 | 更新日期: 2023-09-27 18:11:55

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

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日的东西,它也不会添加或看到任何东西。

c#添加在日期之间的项

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

// 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(...);
}

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

DateTime fromTime;
DateTime toTime;
DateTime currentTime = DateTime.Now;
if (currentTime >= fromTime && currentTime <= toTime)
{
 //to do some stuff
}

效果如下:

var dateFrom = new DateTime(yearFrom, monthFrom, dayFrom);
var dateTo = new DateTime(yearTo, monthTo, dayTo);
var actualDate = new DateTime(year, month, day);
if ((dateFrom < actualDate) && (actualDate < dateTo))
{
    // Do something
}

如果您分别比较日期的各个部分,它将不起作用(正如您已经发现的那样:-D)

为什么不从from和toDate以及实际日期中创建一个日期呢?>

if(fromDate < date && date <= tillDate)
{
}