有两个文本框,txtDateB和txtDateE,分别用来输入开始日期和结束日期,数据库中对应的是表中的DATE字段,用户输入要查询的时间点,两个文本框都可以为空,查询语句该如何写?如何转化txtDateB.Text??下面的语句不能得到答案。
if (!txtDateB.Text.Trim().Equals(""))
{
sql += "and (date > '" + txtDateB.Text.Trim() + "')";//选取录入日期大于查询日期的数据
}
if (!txtDateE.Text.Trim().Equals(""))
{
sql += "and (date < '" + txtDateE.Text.Trim() + "')";//选取录入日期小于查询日期的数据
}
if (!txtDateB.Text.Trim().Equals(""))
{
sql += "and (date > '" + txtDateB.Text.Trim() + "')";//选取录入日期大于查询日期的数据
}
if (!txtDateE.Text.Trim().Equals(""))
{
sql += "and (date < '" + txtDateE.Text.Trim() + "')";//选取录入日期小于查询日期的数据
}
用MaskedTextBox可以规范输入内容
datetime dtTo =Convert.toDateTime(txtDateE.Text)
select * from table where date between dtFrm and dtTo
{
sql += "and (date > '" + txtDateB.Text.Trim() + "')";//选取录入日期大于查询日期的数据
}
if (!txtDateE.Text.Trim().Equals(""))
{
sql += "and (date < '" + txtDateE.Text.Trim() + "')";//选取录入日期小于查询日期的数据
}你是在winform还是网页如果是winform 有个日期选择器,datetimePickersql += "and (date > '" + txtDateB.Text.Trim() +“ 00:00:00”+ "')";//开始时间另外你得txtdatab如果就是textbox的话,那么肯定要先转换的·
如果别人是1111输入我就不知道你的日期是怎么判断得了·= =
{
sql += string.Format("and (date >= '{0}')" , txtDateB.Text.Trim());//选取录入日期大于查询日期的数据
}
if (!txtDateE.Text.Trim().Length > 0)
{
sql += string.Format("and (date <= '{0}')", DateTime.Parse(txtDateE.Text.Trim()).ToString("yyyy-MM-dd") + " 23:59:59");//选取录入日期小于查询日期的数据
}
string endTme = txtDateE.Text;
DateTime sTime = DateTime.MinValue;
DateTime eTime = DateTime.MinValue;
DateTime.TryParse(starTime, out sTime);
DateTime.TryParse(endTme, out eTime);
if (sTime != DateTime.MinValue && eTime != DateTime.MinValue && eTime > sTime)
{
sql += " and date between " + sTime.ToString() + " and " + eTime.ToString();
}else if(sTime!=DateTime.MinValue)
{
sql += " and date > " + sTime.ToString();
}
else if (eTime != DateTime.MinValue)
{
sql += " and date <" + eTime.ToString();
}
如果不为空的话 用下面的正则表达式写的方法 是否为日期格式
两个日期之间的数据 用 between and public bool isdates(string str)
{
bool _isDate = false;
string matchStr = "";
matchStr += @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) ";
matchStr += @"(\s(((0?[0-9])|([1-2][0-3]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$ ";
RegexOptions option = (RegexOptions.IgnoreCase | (RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace));
if (Regex.IsMatch(str, matchStr, option))
{
_isDate = true;
}
else
{
_isDate = false;
} return _isDate;
}