前台有两个TextBox控件,一个ID为datestart,一个ID为dateend,分别标识开始和结束的日期。用来从新闻表中查询发表日期在datestart和dateend之间的文章。
现在我在后台获取这两个TextBox的输入值,
              string datestart = this.datestart.text.tostring().trim();
            string dateend = this.dateend.text.tostring().trim();
定义sql语句;
            string whereStr="select * from Xk_Content";
              if (datestart.Length > 0)
            {
                string startstr = datestart.ToString().Trim();
                DateTime dt1 = DateTime.ParseExact(datestart, "yyyy-MM-dd HH:mm:ss", null);
                whereStr += " and AddDate > '" + dt1 + "' ";
            }
            if (dateend.Length > 0)
            {
                string endstr = dateend.ToString().Trim();
                DateTime dt2 = DateTime.ParseExact(dateend, "yyyy-MM-dd HH:mm:ss", null);
                whereStr += " and AddDate < '"+dt2+"' ";
            }
然后执行查询!
为什么会提示:该字符串未被识别为有效的 DateTime。

解决方案 »

  1.   

    "yyyy-MM-dd HH:mm:ss"
    你那个冒号用了中文的冒号,改为英文冒号试试看?
      

  2.   

    你是在textbox输入值转换的时候出错的吧?DateTime.ParseExact(datestart, "yyyy-MM-dd HH:mm:ss", null); 
     or 
    DateTime.ParseExact(dateend, "yyyy-MM-dd HH:mm:ss", null); 单步调试一下.datestart和dateend的值,仔细看下
      

  3.   

    首先,你输入的字符串,是否能够转换为DateTime?
    其次,whereStr += " and AddDate < '"+dt1+"' " 和whereStr += " and AddDate < '"+dt2+"' "
    这两句,在时间类型后面加上ToString()
      

  4.   

    "yyyy-MM-dd HH:mm:ss"
    全角冒号吗?
      

  5.   

    DateTime dt1 = DateTime.ParseExact(datestart, "yyyy-MM-dd HH:mm:ss", null); 里的":"这个符号要用半角的
      

  6.   

    在SQL里面"'是用来标识字符串用的。
    要标识时间日期用#
      

  7.   

    yyyy-MM-dd HH:mm:ss 格式是这个,那么你输入的格式应该是:2008-01-01 00:00
      

  8.   

    我改了,输入的是“:”了,还是不行!
    该字符串未被识别为有效的 DateTime。
    if (datestart.Length > 0)
    行 22:         {
    行 23:             DateTime dt1 = DateTime.ParseExact(datestart, "yyyy-MM-dd HH:mm:ss", null);
      

  9.   

    既然指定了格式和ParseExact,就要严格按照格式要求输入
      

  10.   

    我的数据库里面的字段AddDate
    的数据类型是smalldatetime
    和这个有关系吗?
      

  11.   

    如果没有时分秒,这样就可以了:        string a = "2008-01-01";
            DateTime d = Convert.ToDateTime(a);
      

  12.   

    whereStr 不全吧 select * from XX where 1=1 and .....
      

  13.   

    时间格式不对,就是上面说的输入格式不对若要输入2008-11-26
    可以在sql查询的时候转换一下datetime@endtime=convert(varchar(10),endtime,120)