注册 登录
编程论坛 ASP.NET技术论坛

请教一个关于日期时间的问题

suhoo 发布于 2006-05-03 21:08, 761 次点击
小弟在这请教一个问题,请各位高手帮帮忙
我想统计一下今日发帖的总帖数:
System.DateTime currentTime=System.DateTime.Now; //这个是得到当前时间
string temptime=currentTime.ToString("yyyy-MM-dd");
sql="select count(*) from pub where P_time like '"+temptime+"%'";
this.lbtonum.Text=DataOperate.CreateTotal(sql);

CreateTotal是在DataOperate页面的:
public static string CreateTotal(string sql)
{
SqlConnection con=DataOperate.con();
con.Open();
SqlCommand cmd=new SqlCommand();
cmd.CommandText=sql;
cmd.Connection=con;
string total=cmd.ExecuteScalar().ToString();
return total;
con.Close();
}

数据库的j时间格式j是2006-06-03 15:45:11
temptime输出的格式是2006-06-03证实过的
运行是通过的,而我发过帖子测试,但是好像没有执行到,在页面显示的是0,
请高手指点指点
小弟在这先谢谢大家了。
7 回复
#2
lhb3182006-05-04 11:18
string total=cmd.ExecuteScalar().ToString("d");
#3
小笨笨2006-05-04 16:28

sql="select count(*) from pub where P_time like '"+temptime+"%'";

这一句有问题,如果你的P_time是日期型的,用like可能会得不到你要的效果。所以count(*)的结果为0.

你可以在sql分析器里看看查询出来的结果是不是0

#4
caiyakang2006-05-04 18:42
原来是小冲
#5
suhoo2006-05-07 13:32

谢谢各位的帮忙!请问笨笨姐,我的P_time如你所说的是日期型,那么要想得到那种效果,应该如何改呢?

#6
小笨笨2006-05-07 17:31


如果你想统计当天的数据的话,如2006年4月12日的数据,可以用

select count(*) from pub where (P_time < CONVERT(DATETIME, '2006-04-12 00:00:00', 102)) AND
(P_time > CONVERT(DATETIME, '2006-04-11 00:00:00', 102))

前提是,你的P_time必须是日期型的。

#7
suhoo2006-05-07 18:46

谢谢笨笨姐,我试一下看看!

1