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

ASP.NET MVC5中如何用LINQ筛选与当前日期匹配的数据库记录

Fixing Date Filtering for LocalTeaTbl Records

First off, I spot a critical bug in your date formatting code that’s almost certainly causing mismatches: you’re using mm in your format string, which represents minutes, not months. You need to use MM (uppercase) for months instead. That’s why your date string might end up looking like 15-30-2024 instead of 15-05-2024—definitely not what you want!

Beyond that, let’s cover two approaches depending on how your database stores the Dated column:

Scenario 1: Dated is stored as a string (varchar/text)

If your database’s Dated column is explicitly stored as a string in dd-MM-yyyy format, here’s the corrected code:

IEnumerable<LocalTeaTbl> GetAllOrbat() 
{
    // Fix: Use MM for months instead of mm
    string date = string.Format("{0:dd-MM-yyyy}", DateTime.Now);
    
    using (PostOfficeEntities2 db = new PostOfficeEntities2()) 
    {
        List<LocalTeaTbl> print = db.LocalTeaTbls
            .Where(x => x.Dated == date)
            .ToList();
        return print;
    }
}

If your Dated column is a proper DateTime type (the best practice for date storage), you shouldn’t convert it to a string for comparison. Instead, compare the date part directly to avoid issues with time components:

IEnumerable<LocalTeaTbl> GetAllOrbat() 
{
    DateTime today = DateTime.Today; // Gets current date with time set to midnight
    
    using (PostOfficeEntities2 db = new PostOfficeEntities2()) 
    {
        List<LocalTeaTbl> print = db.LocalTeaTbls
            // Compare only the date portion of Dated to today's date
            .Where(x => x.Dated.Date == today)
            .ToList();
        return print;
    }
}

This second approach is superior because:

  • It skips unnecessary string parsing overhead
  • Eliminates risks of locale or format mismatches
  • Lets the database use indexes on the Dated column for faster queries

Quick Reminder:

  • Never mix up mm (minutes) and MM (months) in date format strings—this is a super common gotcha!
  • Whenever possible, store dates as DateTime types in your database to avoid these kinds of pitfalls entirely.

内容的提问来源于stack exchange,提问作者Do You Know

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:33:28