检查给定数据是否位于数据表中的两个特定日期之间

时间:2012-07-18 08:17:27

标签: c# .net database date

我有一个DataTable dt,其中有两列FromDateToDate。我有两个文本框,我输入日期blackOutFromDateblackOutToDate。说,我的DataTable dt中有7行:

From Date       To Date      
8/21/2012   To  8/22/2012   
8/23/2012   To  8/24/2012   
8/25/2012   To  8/25/2012   
8/5/2012    To  8/6/2012    
8/26/2012   To  8/27/2012   
8/1/2012    To  8/2/2012    
8/3/2012    To  8/3/2012

如果我在文本框CheckInDateCheckOutDate中输入的值介于DataTable dt的任何匹配日期范围之间,那么它应返回具有此类值的行的数量为noumber的行数匹配。

我在做

foundRows = _blackOutTable.Select
                               (
                                   "(FromDate <='" +     
blackOutFromDate.ToShortDateString() + "' AND ToDate >= '" + 
blackOutFromDate.ToShortDateString() + "')"
                                   + "OR (FromDate <='" + 
blackOutToDate.ToShortDateString() + "' AND ToDate >='" + 
blackOutToDate.ToShortDateString() + "')"
                                   + "OR (FromDate >='" + 
blackOutFromDate.ToShortDateString() + "' AND FromDate <='" +     
blackOutToDate.ToShortDateString() + "')"
                                   + "OR (ToDate >= '" +   
blackOutFromDate.ToShortDateString() + "' AND ToDate <='" +     
blackOutToDate.ToShortDateString() + "')"
                               );
if (foundRows.Length == 0)
{
}

编辑: 我将DateFrom和DateTo存储在SQl Server中作为

CAST(MONTH(date1) AS VARCHAR(2)) + '/' + CAST(DAY(date1) AS VARCHAR(2)) + '/' +     
CAST(YEAR(date1) AS VARCHAR(4))  [fromdate],
        CAST(MONTH(date2) AS VARCHAR(2)) + '/' + CAST(DAY(date2) AS 
VARCHAR(2)) + '/' + CAST(YEAR(date2) AS VARCHAR(4))  [todate]

blackOutFromDate和blackOutFromDate属于DateTime类型。

但它没有返回正确的值。 select表达式存在一些问题。我该怎么做才能解决这个问题?

3 个答案:

答案 0 :(得分:0)

这是DataTable.Select语法for DateTimes

foundRows = _blackOutTable.Select("FromDate >= #2012-07-13#")

因此您需要使用String.Format将日期变量放入该字符串中。

编辑:由于您的日期时间已转换为varchar且无法更改,因此您需要将它们解析回日期时间。我建议使用Linq-To-DataSet

DataTable tblFiltered;
var invCulture=System.Globalization.CultureInfo.InvariantCulture;
var filteredRows = _blackOutTable.AsEnumerable()
    .Where(r => DateTime.Parse(r.Field<String>("FromDate"), invCulture) >= blackOutFromDate
             && DateTime.Parse(r.Field<String>("ToDate"),   invCulture) <= blackOutToDate);

if (filteredRows.Any())
{
    tblFiltered = filteredRows.CopyToDataTable();
}

您可以使用foreach枚举所有行,或使用CopyToDataTable从过滤后的DataTable创建新的DataRows

答案 1 :(得分:0)

为什么不在数据库上执行此操作?

WHERE (1=1) 
AND 
( 
    @in_ReportingDate BETWEEN Cast(Floor(Cast(ZO_RMArea_DateFrom As Float)) As DateTime) AND Cast(Floor(Cast(ZO_RMArea_DateTo As Float)) As DateTime) 
    OR ZO_RMArea_DateFrom IS NULL 
    OR ZO_RMArea_DateTo IS NULL 
) 

另外注意 - 你有DateTime值,如果你做ToShortDateString,它将是date.00:00:00.000,而FromDate可以是date.23:59:59.995

这就是Cast(Floor(Cast)用于。截断比较中的时间。

答案 2 :(得分:0)

试试这个

int rowCount = blackOutTable.AsEnumerable()
            .Count(c => ((DateTime)c["FromDate"]) >= blackOutFromDate && ((DateTime)c["ToDate"]) <= blackOutToDate);