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

C#查询今日、过往、明日预约列表的DateTime筛选逻辑问题

问题原因分析

你原来使用==匹配不到今日预约的根因:DateTime.Now.Date返回的是当日零点整的DateTime值,而StartDateTimeBooking存储了具体时分秒信息,只有恰好是零点的预约才会匹配相等条件,因此查询结果为空。

你提交的筛选逻辑正误判断
  • 今日预约筛选逻辑:正确。采用「左闭右开」的区间判断是DateTime日期范围筛选的最佳实践,能完全覆盖今日0点到次日0点前的所有时间,避免因毫秒精度、闰秒等边界问题漏判或误判。
  • 仅明日预约筛选逻辑:存在边界错误。你当前写的StartDateTimeBooking > today.AddDays(1)会漏掉明日0点整的预约,需要把>改为>=,修正后为:
.Where(e => e.StartDateTimeBooking >= today.AddDays(1) && e.StartDateTimeBooking < today.AddDays(2))
  • 未来所有预约筛选逻辑:正确,>= today会匹配今日零点及之后的所有预约。
  • 过往预约筛选逻辑:正确,< today会匹配今日零点之前的所有历史预约。
重复代码优化方案

你可以提取公共查询逻辑,避免不同筛选场景重复写Include、排序等代码,示例如下:

// 提取公共查询方法
private IList<Appointment> GetAppointmentsByFilter(Expression<Func<Appointment, bool>> filter)
{
    return db.Appointments
        .Where(filter)
        .Include(e => e.Patient) 
        .ThenInclude(p => p.User)
        .Include(e => e.Doctor) 
        .ThenInclude(d => d.User)
        .OrderBy(d => d.StartDateTimeBooking)
        .ToList();
}

// 今日预约
public IList<Appointment> GetTodaysAppointments()
{
    DateTime today = DateTime.Now.Date;
    return GetAppointmentsByFilter(e => e.StartDateTimeBooking >= today && e.StartDateTimeBooking < today.AddDays(1));
}

// 明日预约
public IList<Appointment> GetTomorrowsAppointments()
{
    DateTime today = DateTime.Now.Date;
    return GetAppointmentsByFilter(e => e.StartDateTimeBooking >= today.AddDays(1) && e.StartDateTimeBooking < today.AddDays(2));
}

// 过往预约
public IList<Appointment> GetPastAppointments()
{
    DateTime today = DateTime.Now.Date;
    return GetAppointmentsByFilter(e => e.StartDateTimeBooking < today);
}

// 未来所有预约
public IList<Appointment> GetFutureAppointments()
{
    DateTime today = DateTime.Now.Date;
    return GetAppointmentsByFilter(e => e.StartDateTimeBooking >= today);
}

补充提示:如果你的应用服务跨时区部署,建议统一存储UTC时间,筛选时使用DateTime.UtcNow.Date替代DateTime.Now.Date,避免时区偏移导致的筛选偏差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:27:03