ASP.NET MVC5中如何用LINQ筛选与当前日期匹配的数据库记录
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; } }
Scenario 2: Dated is stored as a DateTime type (recommended)
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
Datedcolumn for faster queries
Quick Reminder:
- Never mix up
mm(minutes) andMM(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

