我正在构建一个 Web 应用程序,它将显示存储在 SQL Server 2008 数据库中的人员列表即将到来的生日。我无法弄清楚如何查询数据库中距今天日期 30 天内的所有记录。
这是我目前所拥有的:
using (HumanResourcesDB db = newH umanResourcesDB(ConfigurationManager.ConnectionStrings["HumanResourcesDB"].ConnectionString))
{
DateTime todaysDate = DateTime.Now;
List<Employee> record =
(from tab in db.Employees
where tab.Birthday between DateTime.Now and todaysDate.AddDays(30)
select tab).ToList();
this.grdBirthdays.DataSource = record;
this.grdBirthdays.DataBind();
}
当然“between”和“and”不起作用,这就是我需要填写的。我在网上搜索了一段时间没有结果。有帮助吗?
最佳答案
只需使用大于和小于
using (HumanResourcesDB db = newHumanResourcesDB(ConfigurationManager
.ConnectionStrings["HumanResourcesDB"].ConnectionString))
{
List<Employee> record = (from tab in db.Employees
where tab.Birthday >= DateTime.Today
&& tab.Birthday < DateTime.Today.AddDays(31)
select tab).ToList();
this.grdBirthdays.DataSource = record;
this.grdBirthdays.DataBind();
}
另外,我应该提到我使用的是 DateTime.Today 而不是 DateTime.Now,因为今天表示一天的开始时间为 00:00:00.000。如果某人的生日设置为今天 00:00:00.000 并且您使用了 DateTime.Now(假设现在是早上 8:00)。生日不包括在这个范围内,因为它被认为是在“现在”之前。
关于c# - 在 C# 中从 SQLServer 查询日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9403507/