thalapathy thalapathy - 1 month ago 22
ASP.NET (C#) Question

Compare DateTime with 24 hours

``I have a method to retrieve DateTime from MS Acesss. I want to allow a client to cancel his booking up to 24 hours prior to the date. How can I code this using if else statement?

this is my method.

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


How to code if else statement like
string d = db.date(id);
DateTime n = Convert.toDateTime(d);

if ( n <= 24 hours???){
do.this....
}

Answer

make a method like this

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


}

then call it

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