比较DateTime和24小时

本文关键字:24小时 DateTime 比较 | 更新日期: 2023-09-27 18:13:11

' '我有一个方法来检索DateTime从MS访问。我想允许客户在约会前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();
        }
    }

如何编写if else语句字符串d = db.date(id);DateTime n = Convert.toDateTime(d);
If (n <= 24小时??){do.this……}

比较DateTime和24小时

创建如下方法

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();
        }
    }

你可以根据你的需求修改你的函数,但希望下面能给你一个想法:

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
}