楼主要相减的话这么做,以下两种方式都可以
DateTime dt1 = DateTime.Now.AddHours(12);
DateTime dt2 = DateTime.Now;
TimeSpan TimeS = default(TimeSpan);
TimeS = dt1 - dt2;
Response.Write(dt1.ToString());
Response.Write("");
Response.Write(dt2.ToString());
Response.Write("");
Response.Write("相差时间:" + TimeS.Hours.ToString());
Response.Write("");
Response.Write("相差时间:" + (dt1 - dt2).Hours.ToString);
建议 你 time1和time2
不要使用 string类型,用DataTime类型
这样,你的代码比较拗好看。用太多的Convert 这样性能会有一定影响
我看你的代码,不清楚这个代码是不是 Web应用程序。如果是Web应用程序的话。你的 time1,在单击Button11之后可能是 个 空字符串(“”)。
如果是windows 应用程序的话,你必须点完前面两个按钮,才能正常运行
首先.在绑定的时候.没必要先转为DateTime格式.直接这么写就OK:
<%# Eval("LastLoginTime","")%>
报错的话.也许是你数据的问题.可能有空值.或其它的.所以你先直接用
<%# Eval("LastLoginTime") %>
输出看看结果.是不是有非DateTime的串.如果有空值的话这么写:
<%# Eval("LastLoginTime").ToString().Length > 0 ? Eval("LastLoginTime", "") : "---"%>
获得开始时间和结束时间的这两段代码,你不觉得都是获得系统时间的操作吗?
以下是计算时间差的简化操作:
string sql="select * from time";
DataTable dt=DBhelper.CommonCha(sql)
if(dt.Rows.count>0)
{
this.textBox1.Text=DateTime.Now.ToString();
this.textBox2.Text=dt.Rows[0][endtime].Tostring;
}
/*由于时间是DateTime类,计算时,要将string类转换*/
DateTime begintime=convert.ToString(this.textBox1.Text)
DateTime endtime=convert.ToString(this.textBox2.Text)
TimeSpan ts=endtime-begintime;
/*转换成小时*/
int hours=(int)ts.Totalhours;
time1和time2中是空值,当然会报错了,你把time1和time2设置为静态的就可以的
比如
static string time1=string.Empty;
static string time2=string.Empty;
PS:string类型赋空值最好用string.Empty,不要用""