You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataTable搜索MSSQL datetime列无结果,寻求技术指导

解决Datetime列搜索无结果的问题

问题根源

你的代码里,前端用moment把DateCreated格式化为DD-MM-YYYY HH:mm:ss A(比如05-10-2024 10:30:00 AM),但后端直接调用x.DateCreated.ToString()时,MSSQL的datetime类型转字符串的默认格式取决于服务器区域设置(比如可能是MM/dd/yyyy HH:mm:ss或其他格式),和前端显示的格式完全不匹配,自然搜不到结果。

解决方案

方案1:统一前后端日期字符串格式

后端把DateCreated转成和前端完全一致的格式后再做包含匹配,确保字符串能对应上:

// 替换原Where中的DateCreated判断部分
x.DateCreated.ToString("dd-MM-yyyy HH:mm:ss tt").Contains(searchValue)

注意:tt是.NET中对应AM/PM的格式符,和moment的A对应。不过这种方式如果数据量较大,可能会触发EF客户端求值(即先把所有数据拉到内存再过滤),性能会受影响。

方案2:基于日期范围的搜索(推荐)

把用户输入的搜索字符串解析为DateTime对象,通过日期范围查询代替字符串匹配,既能保证准确性,又能利用数据库索引提升性能:

string searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
var culture = CultureInfo.InvariantCulture;
var accountsQuery = dbcontext.ApproveAccounts.AsQueryable();

if (!string.IsNullOrEmpty(searchValue))
{
    // 先尝试匹配完整日期时间格式
    if (DateTime.TryParseExact(searchValue, "dd-MM-yyyy HH:mm:ss tt", culture, DateTimeStyles.None, out DateTime exactDate))
    {
        // 查询该时间点前后1秒内的记录(处理秒级精度)
        accountsQuery = accountsQuery.Where(x => 
            x.UserID.ToString().Contains(searchValue) || 
            (x.DateCreated >= exactDate && x.DateCreated < exactDate.AddSeconds(1)));
    }
    // 再尝试匹配仅日期部分的搜索
    else if (DateTime.TryParseExact(searchValue, "dd-MM-yyyy", culture, DateTimeStyles.None, out DateTime dayDate))
    {
        var startOfDay = dayDate.Date;
        var endOfDay = startOfDay.AddDays(1);
        accountsQuery = accountsQuery.Where(x => 
            x.UserID.ToString().Contains(searchValue) || 
            (x.DateCreated >= startOfDay && x.DateCreated < endOfDay));
    }
    // 仅匹配UserID
    else
    {
        accountsQuery = accountsQuery.Where(x => x.UserID.ToString().Contains(searchValue));
    }
}

var tAccounts = accountsQuery.ToList();

额外注意事项

  • 如果你的DateCreated包含毫秒,解析时可以调整格式字符串加入毫秒部分(比如dd-MM-yyyy HH:mm:ss.fff tt),避免因为精度问题漏查。
  • 尽量避免在数据库查询中对日期字段做字符串转换,优先使用日期范围查询,能有效利用索引优化性能。

内容的提问来源于stack exchange,提问作者Joe Black

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:15:30