简体   繁体   English

比较Datetime SQL Server和ASP.NET

[英]Comparing Datetime SQL server and asp.net

I'm making a function that would cancel an order only if it's within 60 minutes , what I was suggested is to compare the datetime value of the order to the current datetime. 我正在制作一个60分钟内取消订单的函数,建议我将订单的datetime值与当前datetime进行比较。

        using (SqlConnection con = new SqlConnection(Helper.GetCon()))
        {
            con.Open();
            string query = @"SELECT * from [Order] where orderid = @id";
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.Parameters.AddWithValue("@id", id);
                using (SqlDataReader data = cmd.ExecuteReader())
                {
                    DataTable dt = new DataTable();
                    dt.Load(data);
                    foreach (DataRow dr in dt.Rows)
                    {
                        var supplier = new Supplier();
                        supplier.OrderDate = DateTime.Parse(dr["OrderDate"].ToString());
                    }
                }
            }
            return View();

So far I've only taken the datetime from the database, I was wondering how you can get the current datetime and get the difference in let's say minutes or hours so that I can make a conditional statement to allow or not allow the cancellation of an order. 到目前为止,我只从数据库中获取了日期时间,我想知道如何获取当前日期时间并获得分钟小时的差异,以便我可以做出条件语句来允许或不允许取消订购。 I'm fairly new to this and any help would be appreciated! 我对此很陌生,任何帮助将不胜感激! Thank you! 谢谢!

使用DateDiff,将所选日期列与现在进行比较,并使用MINUTE差异:

SELECT DATEDIFF(MINUTE, OrderDate , getdate()) AS MinuteDiff from [Order] where orderid =123

If you must do it in the application rather than the SQL query, you can do something like: 如果必须在应用程序中而不是在SQL查询中执行此操作,则可以执行以下操作:

var timeSinceOrder = DateTime.Now - supplier.OrderDate;

if(timeSinceOrder < TimeSpan.FromHours(1))
{
    //do stuff here
}

DateTime.Now gets the current time. DateTime.Now获取当前时间。 Subtracting the order date from the current time returns a timespan that you can then compare to another timespan, in this case created by the function Timespan.FromHours. 从当前时间中减去订单日期将返回一个时间跨度,然后您可以将其与另一个时间跨度进行比较,在这种情况下,此时间跨度是由功能Timespan.FromHours创建的。

You can also use DateTime.Compare method. 您也可以使用DateTime.Compare方法。 Something like 就像是

If(DateTime.Compare(supplier.OrderDate, DateTime.Now) < 60)
{  
   //Enable Cancel/Delete Order
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM