要转换为日期格式的字符串

时间:2013-09-07 06:38:01

标签: c# asp.net sql

的.aspx:

<asp:TextBox ID="txtend" runat="server"></asp:TextBox></td>

此aspx代码将“date”存储在其文本字段中。

我想在c#中访问此文本字段,其中代码显示为  如何将字符串格式转换为日期类型并进行访问..?

SqlDataAdapter adapter = new SqlDataAdapter(
    "select * from Membership_det where updateDate is between "+txtstart.Text+" and "+txtend.Text+" ", 
    con);

6 个答案:

答案 0 :(得分:1)

您可以使用DateTime.ParseExact进行转换。这样的事情: -

DateTime.ParseExact(txtstart.Text, "yyyyMMdd", null);

旁注: -

正如评论中 Uwe Keim 指出的那样,您的代码很容易SQL injection

如果您使用参数化SQL查询

,那将是一件好事

答案 1 :(得分:1)

    DateTime startDate;
    DateTime endDate;

    if (DateTime.TryParse(txtstart.Text, out startDate) && DateTime.TryParse(txtend.Text, out endDate))
    {
        //string n1 = DropDownList2.SelectedItem.Text;

        if (DropDownList1.SelectedItem.Text == "Membership")
        {
            SqlConnection con = new
      SqlConnection(ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ToString());
            con.Open();
            SqlDataAdapter adapter = new SqlDataAdapter("select p.Name,m.FID,m.MembNo,m.MembType,m.Validity,m.Remarks from Membership_det m INNER JOIN Personal_det p  ON m.FID= p.FID where m.updateDate  between @Start and @End ", con);
            adapter.SelectCommand.Parameters.Add("@Start", SqlDbType.Date).Value = startDate;
            adapter.SelectCommand.Parameters.Add("@End", SqlDbType.Date).Value = endDate;
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            con.Close();
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        log.Debug("Info: Admin viewed the membership details");
    }

答案 2 :(得分:0)

使用此:

DateTime startDate = DateTime.ParseExact(txtstart.Text, "yyyyMMdd", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "yyyyMMdd", null);

SqlDataAdapter adapter = new SqlDataAdapter(
    "select * from Membership_det where updateDate is between "+ startDate.ToString() + " and "+ endDate.ToString() +" ", 
    con);

答案 3 :(得分:0)

使用此

string date = "01/08/2008";
    DateTime dt = Convert.ToDateTime(date); 

||

string date = "Sun, 17 Mar 2013 12:40:23 +0000";
var dt = DateTime.ParseExact(date, "ddd, dd MMM yyyy hh:mm:ss zzz", CultureInfo.InvariantCulture);

答案 4 :(得分:0)

您的文本框日期时间类似于“25-09-2013”​​意味着将格式类型设置为“dd-MM-yyyy”,您将获得字符串格式。

E.g:1

var da="2013-09-25";
DateTime.ParseExact(da, "yyyy-MM-dd", 
System.Globalization.CultureInfo.CurrentCulture);

E.g:2

var da="25-09-2013";      
DateTime.ParseExact(da, "dd-MM-yyyy",
System.Globalization.CultureInfo.CurrentCulture);

答案 5 :(得分:0)

SqlDataAdapter adapter = new SqlDataAdapter(
    "select * from Membership_det where updateDate is between '"+ Convert.ToDateTime( txtstart.Text).ToString("dd/MMM/yyyy")+"' and '"+ Convert.ToDateTime( txtend.Text).Tostring("dd/MMM/yyyy")+"' ", 
    con);