从.Net中的SQL数据库获取时间敏感的特定数据

问题描述 投票:0回答:1

我需要帮助来更改我的 API 方法之一。 我有一个数据库,很少有这样的事件:

EventName: Event 1 EventDate: 2013-08-15 00:00:00:00.000 isActive: true

EventName: Event 2 EventDate: 2013-08-16 00:00:00:00.000 isActive: true

EventName: Event 3 EventDate: 2013-08-17 00:00:00:00.000 isActive: true

现在,我有这个方法:

public IQueryable<Event> allActiveAndToday(){
     return this.Where(e => e.IsActive)
}

此方法返回上述所有事件,我想将其更改为仅返回同一日期上午 8:00 到第二天上午 8:00 之间的事件。

例如:

  • 如果该方法在 08/16/2013 上午 7:00 被调用,结果将是
    Event 1
  • 如果该方法在 08/16/2013 上午 9:00 被调用,结果将是
    Event 2
  • 如果该方法在 08/17/2013 上午 7:00 被调用,结果将是
    Event 2
  • 如果该方法在 08/17/2013 上午 9:00 被调用,结果将是
    Event 3

假设这就像每天早上 8:00 开始和结束..

我找不到方法来做到这一点,因为我不熟悉 .net 中的选项和上下文。

c# sql .net linq datetime
1个回答
0
投票

我认为这应该可以做到:

public IQueryable<Event> allActiveAndToday(){
    DateTime currentDt = DateTime.Now;
    DateTime start = new DateTime(currentDt.Year, currentDt.Month, currentDt.Day, 8, 0, 0);
    DateTime end = start.AddDays(1);

    // This will check if the the current date/time falls between 8AM and 8AM (the following day)
    // If not then set the currentDt to yesterday's date.
    if (!(currentDt >= start && currentDt <= end))
    {
        currentDt = currentDt.AddDays(-1);
    }

    // Then do your query here...
    var events = this.Where(x => x.IsActive && x.EventDate.Date == currentDt.Date).ToList();

    return events;
}
© www.soinside.com 2019 - 2024. All rights reserved.