繁体   English   中英

比较DateTime和24小时

[英]Compare DateTime with 24 hours

``我有一种从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语句,例如字符串d = db.date(id); DateTime n = Convert.toDateTime(d);
如果(n <= 24小时???){这样做。...}

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

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
}

做这样的方法

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

暂无
暂无

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

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