I have a records in my table Test like this my Date column is of type varchar.
Fname Lname Date
vivek parikh 01-09-2011 10:00:00 PM
kashyap vyas 02-09-2011 10:50:00 AM
viral panchal 02-09-2011 10:00:00 PM
Arpit Gosai 03-09-2011 10:00:00 PM
Darshit Chokshi 04-09-2011 10:00:00 PM
Sameer Rangrez 24-08-2011 9:15:12 AM
i want to fetch records within date range (start date and end date) from page.
my code is
DateTime time = DateTime.Today; // Use current time
string format = "MM-dd-yyyy";
SqlCommand cmd = new SqlCommand("select Fname,Lname,Insert_Date from Test where Insert_Date >= '" + Convert.ToDateTime(TextBox1.Text).ToString(format) + "' and Insert_Date <= '" + Convert.ToDateTime(TextBox2.Text).ToString(format) + "' ", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Response.Write(ds.Tables[0].Rows[i]["Fname"].ToString());
Response.Write(ds.Tables[0].Rows[i]["Lname"].ToString());
Response.Write(ds.Tables[0].Rows[i]["Insert_Date"].ToString()+"<br>");
}
for building your query use Convert(datetime,fieldname,103) for converting varchar to datetime.
Your query should be something like.
select * from Test
where Convert(datetime,field_date,103) >= ‘2011-01-01’ –start date
and Convert(datetime,field_date,103) <= ‘2012-01-01’; –end date
This is how your C# statement should look like (It should include 103 code to specify your date format which dd-mm-yyyy