简体   繁体   中英

issue with date and time comparision in asp.net c#

i am trying to unreserve a book as the reservation time is 24 hours after its expiry in library automation system but it is not working. following is the code which is not working

 protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            SqlConnection con = new SqlConnection(strcon);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();

            }
            SqlCommand cmd = new SqlCommand("select * from book_reserve_tbl;", con);
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                string todate_str;
                DateTime reserve_todate, current_datetime;
                current_datetime = DateTime.Now;
                string book_id;
                while (dr.Read())
                {

                    todate_str = dr.GetValue(4).ToString(); ;//this will assign the reserveToDate col value
                    String is_reserve = dr.GetValue(5).ToString();
                    reserve_todate = Convert.ToDateTime(todate_str);
                    if (reserve_todate < current_datetime && is_reserve == "YES" )
                    {
                        Response.Write("<script>condition true</script>");
                        book_id = dr.GetValue(1).ToString();
                        UpdateCurrentStock(book_id);
                        UpdateBookReservation(book_id);
                    }

                    
                }
                con.Close();
                
            }
        }
       
        
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message + "');</script>");
        }
    }

plz help as i have no experience of it

Regards

If you want to calculate time between two DateTime values, you should use TimeSpan:

TimeSpan elapsed;
DateTime time1;
DateTime time2;

elapsed = time1.Subtract(time2);
//or with DateTime.Now
elapsed = DateTime.Now.Subtract(time1);

Never use string to store DateTime values!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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