如何将Linq中的时间划分为实体? [英] how can Divide Time into Shifts in Linq to Entity?
问题描述
我的数据库中有DateTime列我使用以下查询来获取特定日期的数据,
I have DateTime column in my database I use following query to get the data of specific Date,
List<Products> AllProductsByGivenDate(DateTime forDate)
{
var query = ctx.Products.Where(p=>p.DateTime.Value.Year==forDate.Year && p.DateTime.Value.Month==forDate.Month && p.DateTime.Value.Day==forDate.Day).ToList();
return query;
}
现在我还想要检索特定的数据时间间隔如,
12:00 AM至08:30 AM
8:30 AM to 11:45 AM
我的意思是我现在有特定日期的数据我需要选择从上午12:00到上午08:30之间存在的所有记录。 />
我使用p.DateTime.Value.Hour> ='08'&& p.DateTime.Value.Hour< ='12'&& p.DateTime.Value.Minute> = '00'&& p.DateTime.Value.Minute< ='59'
换班如08:00到12:00它很有效但是8:30它也显示8:31到8:59的记录,但我只需要记录从8:30到12:00。
Now I further wants to retrieve the data for specific Time Interval like,
12:00 AM to 08:30 AM
8:30 AM to 11:45 AM
I mean I have the data of specific date now I need to select all records which exists from 12:00 AM to 08:30 AM
I use p.DateTime.Value.Hour>='08' && p.DateTime.Value.Hour<='12' && p.DateTime.Value.Minute>='00' && p.DateTime.Value.Minute<='59'
for a shift like 08:00 to 12:00 it works Perfect but for 8:30 it also shows the records for 8:31 to 8:59 but i need only records from 8:30 to 12:00.
推荐答案
http://stackoverflow.com/questions/21812833/dividing-entities-into-groups [ ^ ]
首先,你应该有正确理解小时> = 08 &&小时< = 12 &&分钟> = 00 &&分钟< = 59表示08:00到12:59之间的时段。
但是,小时> = 08 &&小时< = 12 &&分钟> = 30 &&分钟< = 59表示08:30~8:59,09:30~9:59,...,12:30 〜12:59。
拿到这个?小时和分钟不分!
如果你想在它之间做8:30和12:00,你必须将你的p.DateTime视为DateTime而不是String或Int。
现在,剩下的就是你的工作。
First, you should have a correct understanding of "Hour>=08 && Hour<=12 && Minute>=00 && Minute<=59" means the period between 08:00 and 12:59.
But,"Hour>=08 && Hour<=12 && Minute>=30 && Minute<=59" means 08:30~8:59,09:30~9:59,...,12:30~12:59.
Get this? Hour and minute can be not divided!
If you want to make it between 8:30 and 12:00, you have to treat your p.DateTime as a "DateTime" instead of a "String" or "Int".
Now, the rest is your work.
解决了,
此代码将显示从7:30到16:00的所有记录
Solved,
This code will show all records from 7:30 to 16:00
TimeSpan startTime= new TimeSpan(7, 30, 0);
TimeSpan endTime= new TimeSpan(16, 00, 0);
List<Products> shift= ctx.Products.Where(p => p.DateTime.Value.TimeOfDay >= startTime && p.DateTime.Value.TimeOfDay <= endTime).ToList();
这篇关于如何将Linq中的时间划分为实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!