C# asp.net c中日期和时间比较的问题
我正在尝试取消预订一本书,因为在图书馆自动化系统中预订时间是到期后24小时,但它不起作用。以下是不起作用的代码C# asp.net c中日期和时间比较的问题,c#,C#,我正在尝试取消预订一本书,因为在图书馆自动化系统中预订时间是到期后24小时,但它不起作用。以下是不起作用的代码 protected void Page_Load(object sender, EventArgs e) { try { SqlConnection con = new SqlConnection(strcon); if (con.State == ConnectionState.Closed)
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>");
}
}
请帮忙,因为我没有这方面的经验
关于如果要计算两个日期时间值之间的时间,应使用TimeSpan:
TimeSpan elapsed;
DateTime time1;
DateTime time2;
elapsed = time1.Subtract(time2);
//or with DateTime.Now
elapsed = DateTime.Now.Subtract(time1);
永远不要使用字符串来存储日期时间值 太好了。。。实际的问题是什么?此外,最好将datetime存储为数据库中的实际日期-时间结构,而不是字符串(如果您的数据库有这样的功能),您可能需要指定它不工作的方式,最好有一些输入数据和观察到的行为与预期行为的例子,这将使帮助变得更容易。到目前为止,我唯一想到的是时区。。确保您正在比较同一时区内的时间,如果没有,则需要通过执行datetime.UtcNow.AddHoursx使当前的_datetime变量与数据库字段的时区相匹配,其中x是所需时区的偏移量,最好将DB date字段存储为UTC,并仅使用datetime.UtcNow。但是,正如其他人所说,在我们提供猜测以外的任何信息之前,这个问题需要更详细的信息。感谢大家提供repl.user reserve book,仅限24小时,24小时后其预订应过期/取消。现在在SQLSRVER中,我有一个DateTime数据类型的字段,而不仅仅是字符串。现在,当我比较给定代码中的日期时间时,它不起作用。可能有一个原因,当前的_datetime变量格式是24/09/2020 12:52:40 PM,数据库中的存储是2020-09-24 12:52:40.000。如果格式不同,可能会出现问题,但如何使用以下格式24/09/2020 12:52:40在sql server数据库中保存日期时间。请确认reserve\u todate