将DateTime与24小时进行比较

时间:2016-10-16 05:14:24

标签: c# asp.net

``我有一种从MS Acesss检索DateTime的方法。我想允许客户在日期前24小时取消预订。如何使用if else语句对此进行编码?

这是我的方法。

    public static string Date(int c)
    {
        string a;
        OleDbConnection myconn = DBConn();
        string myQ = "SELECT DateTime FROM Booking WHERE movie_ID=" + c;
        OleDbCommand myCmd = new OleDbCommand(myQ, myconn);
        try
        {
            myconn.Open();

            a = myCmd.ExecuteScalar().ToString();


            return a;

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception in DBHandler", ex);
            return null;
        }
        finally
        {
            myconn.Close();
        }
    }

如果else语句如何编码        string d = db.date(id);        DateTime n = Convert.toDateTime(d);
       if(n <= 24小时???){        做这个....       }

2 个答案:

答案 0 :(得分:1)

您可以根据自己的要求修改功能,但希望下面给出一个想法:

try
    {
        myconn.Open();
        a = myCmd.ExecuteScalar().ToString();
        DateTime DateFromAccess = Convert.ToDateTime(a);

       TimeSpan difference = DateFromAccess.Subtract(DateTime.Now);
       if (difference.TotalHours > 24)
          //Your Code to Cancel Booking
       else
          //"Booking can not be cancelled now";

        return a;
    }

catch(Exception){
    //Handle exception
}

答案 1 :(得分:1)

制作一个像这样的方法

public static bool canCancel(string date)
{
    DateTime booking = Convert.ToDateTime(date);
    DateTime ending = booking.AddHours(23).AddMinutes(59).AddSeconds(59);

    var n = DateTime.Compare(ending, DateTime.Now);
    if(n == -1)
    {
       // within 24 hour from booking
       // so can not cancel
       return false;
    }
    else
    {
       // greater than 24 hour
       // so can cancel
       return true;
    }


}

然后调用它

public static string Date(int c)
    {
        string a;
        OleDbConnection myconn = DBConn();
        string myQ = "SELECT DateTime FROM Booking WHERE movie_ID=" + c;
        OleDbCommand myCmd = new OleDbCommand(myQ, myconn);
        try
        {
            myconn.Open();

            a = myCmd.ExecuteScalar().ToString();

            var can_cancel = canCancel(a);
            return a;

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception in DBHandler", ex);
            return null;
        }
        finally
        {
            myconn.Close();
        }
    }