[英]Comparing a DateTimeOffSet From DataBase to Current Value
What I want to do is simple.我想做的很简单。 If the
DateTimeOffSet
of a created Event is older than 24 hours I want it removed from the database.如果创建的事件的
DateTimeOffSet
早于 24 小时,我希望将其从数据库中删除。 I am having a huge amount to trouble working with Converting System.Linq.IQueryable
to System.DateTime
.我在将
System.Linq.IQueryable
转换为System.DateTime
时遇到了很多麻烦。
Any help will be greatly appreciated.任何帮助将不胜感激。 This is the Index of Events
这是事件索引
public ActionResult Index()
{
IQueryable<DateTimeOffset> b = db.Events.Select(x => x.EventTime);
DateTimeOffset currentDate = DateTimeOffset.Now;
if (currentDate > b)
{
db.Events.Remove(@event);
db.SaveChanges();
return View(db.Events.ToList());
}
return View(db.Events.ToList());
}
My other question is how could I structure this so that it requires a 24 hour difference in order to remove the row from database.我的另一个问题是我如何构造它,以便它需要 24 小时的差异才能从数据库中删除该行。
The data table has the EventTime as a DateTimeOffset
data type.数据表将 EventTime 作为
DateTimeOffset
数据类型。
I have also been trying to use我也一直在尝试使用
DateTimeOffset.Compare(currentDate, b);
But Visual Studio isn't liking that line as well.但是 Visual Studio 也不喜欢这条线。 Please help if you know how to compare a time from a database to current time.
如果您知道如何将数据库中的时间与当前时间进行比较,请提供帮助。 There is really nothing like this in regards on this site.
在这个网站上真的没有这样的事情。 I Have spent all day on this site and have yet to find something along this.
我在这个网站上花了一整天,还没有找到相关的东西。
Thanks谢谢
It might be easier to do the comparison in the query:在查询中进行比较可能更容易:
public ActionResult Index()
{
DateTimeOffset currentDate = DateTimeOffset.Now.AddDays(-1);
IQueryable<Event> events = db.Events.Where(x => currentDate > x.EventTime);
foreach(var e in events){
{
db.Events.Remove(e);
}
db.SaveChanges()
return View(db.Events.ToList());
}
You can then loop through and remove each one.然后,您可以循环遍历并删除每一个。 I would also do save changes outside the loop so that we are committing changes once and not several times.
我也会在循环外保存更改,以便我们提交一次而不是多次更改。
You could do something like this你可以做这样的事情
foreach (var a in b)
{
if( (currentDate - a).Hours >= 24 )
{
...
}
}
See the example here: https://msdn.microsoft.com/en-us/library/bb352700(v=vs.110).aspx请参阅此处的示例: https : //msdn.microsoft.com/en-us/library/bb352700(v=vs.110).aspx
currentDate - b
would return a TimeSpan
object, and you could use the Hours
property on it to do the check. currentDate - b
将返回一个TimeSpan
对象,您可以使用它的Hours
属性进行检查。
See all TimeSpan members here: https://msdn.microsoft.com/en-us/library/system.timespan_members(v=vs.90).aspx在此处查看所有 TimeSpan 成员: https ://msdn.microsoft.com/en-us/library/system.timespan_members( v= vs.90).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.