如何在 DateTime.AddHours() 上使用变量
本文关键字:变量 DateTime AddHours | 更新日期: 2023-09-27 18:32:24
我有来自数据库(int)的测试变量。我需要在 DateTime.AddHours 上使用此变量。
我试过了:
DateTime.Now.AddHours(-<%#test%>)
从数据库测试 = 100
所以它必须是这样的:
DateTime.Now.AddHours(-100)
但是编译器得到错误:
CS1040: Preprocessor directives must appear as the first non-whitespace character on a line
我该如何解决它?
从公共页面加载进行测试:
OleDbConnection Connection;
Connection = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" +
Server.MapPath("~/db.mdb"));
OleDbCommand Command1,
Command1 = new OleDbCommand("SELECT FTPTARIHARALIGI FROM Table1 WHERE ID = 1", Connection);
Connection.Open();
int test = (int)Command1.ExecuteScalar();
我需要在其他类(网格视图行)中使用此变量
public void GridView2_RowDataBound(Object sender, GridViewRowEventArgs e)
{
DateTime dt;
if (DateTime.TryParseExact(e.Row.Cells[2].Text, "yyyyMMddHHmm",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
if (dt <= DateTime.Now.AddHours(test * -1))
{
// ...
如果test
类型为int
,则可以这样做:
DateTime.Now.AddHours(test * -1);
或:
DateTime.Now.AddHours(0 - test);
更新:
您的问题是test
Page_load
方法中的局部变量。
使其全局,并在Page_Load
外部声明:
YourClass
{
int test = 0;
PageLoad Method
{
// set test here
test = (int)Command1.ExecuteScalar();
}
GirdDataRowBound Event
{
// use it here now accessible as it is global
if (dt <= DateTime.Now.AddHours(test * -1))
}
}
你缺少=
尝试:
DateTime.Now.AddHours(-<%=test%>)
<%# is a data binding syntax for use in databound controls.
<%= is a short cut for Response.Write.
<%@ is a directive to include a namespace, page directives, etc.